如何同步这 9 个线程,以便它们在主线程之前执行?
我想检查大小为 9 的二维数组中行的有效性。每行应包含值(1 到 9)。 为此,我在主线程中创建了一个名为“void* checkingRows(void* arg)”的线程,并将其与 main 连接起来。 然后线程 checkingRows 正在创建另外 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
最佳答案
你问,
How can i synchronize these 9 threads so that they execute before main thread?
,我想你在谈论这些:
checkingRows is creating further 9 threads which are checking validity of each row.
当然,这些不能在 main()
之前运行,至少不能在 main
starts 之前运行,除非你在那个时候启动它们大体时间。你不知道。但我认为您真正想要的只是它们在 main
运行超过某个点之前完成。
这就是 pthread_join
的用途。我看到您已经在 main()
中为其启动的线程使用了该函数,但您可能对这不会影响第二个线程启动的其他线程这一事实感到困惑。
它只是不会自动那样工作。一旦启动,线程就相互独立运行。如果你想等待一个线程完成,那么你必须加入那个特定的线程。在您的情况下,这可能意味着 checkingRows()
应该在它自己终止之前加入它启动的每个线程。
关于c++ - 多线程中的同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55726712/