【问题标题】:Multithreading and pthread_join多线程和 pthread_join
【发布时间】:2013-02-13 10:35:26
【问题描述】:

我的程序从一个文本文件中读取迷宫,然后主程序创建 3 个不同的线程来钻研这个迷宫并寻找出口。当一个线程发现退出时,它会在主线程中发布它的解决方案路径。

在这个迷宫中,存在陷阱,当一个线程遇到这些陷阱时,它们会“死亡”,将该陷阱的位置保存到已发现的陷阱点的全局数组中,以便其他线程知道应该避开哪里。在该线程死亡后,主程序将重新生成另一个线程来代替它并继续遍历迷宫。

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

【问题讨论】:

  • 如果你只加入那些以某种方式准备好的线程呢?喜欢在某处设置标志?
  • 我的线程存储在一个 pthread_t 数组中,所以我可以使用全局整数吗?像这样: pthread_mutex_lock(&mutex); while(!foundSolution) { pthread_cond_wait(&cond, &mutex); pthread_create(threads[exited], NULL, thrd_func, &pathfinder[exited]); }

标签: c++ multithreading pthread-join


【解决方案1】:

使用在 pthreads 中为pthread_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

请注意,使用条件变量时,您需要获取和释放关联的互斥锁。查看pthread_cond_wait 的手册页了解更多详情。

【讨论】:

  • 我想问一个问题,对于工作线程,我是在信号广播之前还是之后(退出之前)解锁互斥锁?
  • 你应该在做信号广播后解锁互斥锁。
猜你喜欢
  • 2011-09-22
  • 1970-01-01
  • 1970-01-01
  • 2020-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多