【发布时间】:2019-09-07 15:37:19
【问题描述】:
如何同步这 9 个线程,以便它们在主线程之前执行?
我想检查大小为 9 的二维数组中行的有效性。每行应包含值(1 到 9)。 为此,我在主线程中创建了一个名为“void* checksRows(void* arg)”的线程,并将其与 main 连接。 然后线程检查行正在创建另外 9 个线程来检查每一行的有效性。
````````````````````````````````````
Pthread_t id1;
pthread_mutex_t mut1;
int arr[9][9] = {
{6,2,4,5,3,9,1,8,7},
{6,6,9,7,2,8,6,3,4},
{8,3,7,6,1,4,2,9,5},
{1,4,3,8,6,5,7,2,9},
{9,5,8,2,4,7,3,6,1},
{7,6,2,3,9,1,4,5,8},
{3,7,1,9,5,6,8,4,2},
{4,9,6,1,8,2,5,7,3},
{2,8,5,4,7,3,9,1,6}
};
````````````````````````````````````
void* rowCheck(void* arg){
int* argument = (int*) arg;
int idx = *argument;
int count = 0;
for(int i = 0; i < 9; i++){
int temp = arr[idx][i];
count = 0;
for(int j = i; j < 9; j++){
if(arr[idx][j] == temp || arr[idx][j] <= 0 || arr[idx][j] >= 10){
count++;
}
if(count > 1){
pthread_mutex_lock(&mut1);
count = 0;
cout<<"ERROR at"<<arr[idx][j]<<endl;
pthread_mutex_unlock(&mut1);
break;
}
}
}
pthread_exit(NULL);
}
````````````````````````````````````
void* checkingRows(void* arg){
int *row = new int;
*row = 0;
for(int i = 0; i<gridSize; i++){
pthread_create(&workerIdRow[i], NULL, &rowCheck, row);
*row = *row + 1;
}
pthread_exit(NULL);
}
`````````````````````````````````
int main(){
pthread_mutex_init(&mut1, NULL);
pthread_create(&id1, NULL, &checkingRows, NULL);
pthread_join(id1,NULL);
retrun 0;
}
````````````````````````````````````
ERROR at 6
ERROR at 6
【问题讨论】:
-
new int和cout的使用表明这是 C++,而不是 C。 -
请注意,
pthread_create(..., &rowCheck, row);中的 row 是一个指针,并且您向每个线程传递相同的指针,与 int 的值是否指向无关。 -
与其使用 pthreads,我建议你看看
std::thread这是可移植的内置线程库... -
您在
main中有retrun(而不是return) -
在调用
pthread_create(&id1,NULL,&checkingRows,NULL)之后立即调用pthread_join(id1,NULL)有什么意义?你为什么不直接打电话给checkintRows(NULL)呢?
标签: c++ multithreading operating-system mutex