Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 多线程和pthread_连接_C++_Multithreading_Pthread Join - Fatal编程技术网

C++ 多线程和pthread_连接

C++ 多线程和pthread_连接,c++,multithreading,pthread-join,C++,Multithreading,Pthread Join,我的程序从一个文本文件中读取迷宫,然后主程序创建3个不同的线程来深入这个迷宫并搜索出口。当线程发现出口时,它将在主线程中发布其解决方案路径 在这个迷宫中,存在陷阱,当一个线程遇到陷阱时,陷阱将“消失”,将陷阱的位置保存到一个已发现陷阱点的全局数组中,以便其他线程知道如何避免。在该线程死亡后,主程序将重新启动另一个线程以取代其位置并继续穿越迷宫 线程可能会也可能不会遇到陷阱,使用pthread_join只会等待特定的线程。如何使主线程同时等待每个线程?使用一个条件变量,该变量在pthreads中为

我的程序从一个文本文件中读取迷宫,然后主程序创建3个不同的线程来深入这个迷宫并搜索出口。当线程发现出口时,它将在主线程中发布其解决方案路径

在这个迷宫中,存在陷阱,当一个线程遇到陷阱时,陷阱将“消失”,将陷阱的位置保存到一个已发现陷阱点的全局数组中,以便其他线程知道如何避免。在该线程死亡后,主程序将重新启动另一个线程以取代其位置并继续穿越迷宫


线程可能会也可能不会遇到陷阱,使用pthread_join只会等待特定的线程。如何使主线程同时等待每个线程?

使用一个条件变量,该变量在pthreads中为
pthread\u cond\t
。让主线程等待条件变量,并在线程结束前让它向条件变量发送信号。在类似这样的伪代码中:

主线程

//spawn first set of threads
while(!done) {
   pthread_cond_wait(&cond, &mutex);
   //spawn another thread
}
//traverse maze
pthread_cond_broadcast(&cond);
//thread exit
工作线程

//spawn first set of threads
while(!done) {
   pthread_cond_wait(&cond, &mutex);
   //spawn another thread
}
//traverse maze
pthread_cond_broadcast(&cond);
//thread exit

请注意,使用条件变量时,需要获取并释放关联的互斥体。查看手册页中的
pthread\u cond\u wait
了解更多详细信息。

使用pthreads中的条件变量
pthread\u cond\t
。让主线程等待条件变量,并在线程结束前让它向条件变量发送信号。在类似这样的伪代码中:

主线程

//spawn first set of threads
while(!done) {
   pthread_cond_wait(&cond, &mutex);
   //spawn another thread
}
//traverse maze
pthread_cond_broadcast(&cond);
//thread exit
工作线程

//spawn first set of threads
while(!done) {
   pthread_cond_wait(&cond, &mutex);
   //spawn another thread
}
//traverse maze
pthread_cond_broadcast(&cond);
//thread exit

请注意,使用条件变量时,需要获取并释放关联的互斥体。查看
pthread\u cond\u wait
的手册页以了解更多详细信息。

如何只加入以某种方式发出信号的线程?比如在某处设置一个标志?我的线程存储在pthread\u t数组中,所以我可以使用一个全局整数来完成吗?如下所示:pthread\u mutex\u lock(&mutex);当(!foundSolution){pthread_cond_wait(&cond,&mutex);pthread_create(threads[exited]、NULL、thrd_func,&pathfinder[exited])}时,您如何只加入已经以某种方式发出信号的线程?比如在某处设置一个标志?我的线程存储在pthread\u t数组中,所以我可以使用一个全局整数来完成吗?如下所示:pthread\u mutex\u lock(&mutex);虽然(!foundSolution){pthread_cond_wait(&cond,&mutex);pthread_create(threads[exited],NULL,thrd_func,&pathfinder[exited])}我想问一个问题,对于工作线程,我是在信号广播之前还是之后(退出之前)解锁互斥体?你应该在信号广播之后解锁互斥体。我想问一个问题,对于工作线程,我是在信号广播之前还是之后(退出之前)解锁互斥锁?您应该在信号广播之后解锁互斥锁。