多次使用同一线程的 POSIX pthread

POSIX pthread using same thread multiple times

本文关键字:线程 POSIX pthread 一线      更新时间:2023-10-16

我目前正在处理的问题,我所相信的,是一个相当简单的问题,我似乎无法解决。

我的程序中有两个线程。线程运行良好,但导致问题的是一个线程的重用。伪代码中的以下内容:

main() {
create thread 1;
create thread 2;
join thread 1;
}
thread 1 {
  while true
    if(some condition)
      join thread 2 
      // Use the returned value from thread 2
}
thread 2 {
  while true
    if(some condition)
      // do something
      exit thread 2(with some return value to thread 1).
}

因此,当线程 1 中满足某些条件时,我希望它终止线程 2,直到它完成,这工作得很好。线程 2 到达 is 条件并退出线程。但是,当我回到线程 1 的 while 循环并再次达到条件时,我希望它再次重新运行线程 2。这就是导致问题的原因。执行线程 2 一次后,线程 1 忽略我的 join 语句,只在 while 循环中轮询,是唯一正在运行的线程。

所以我的问题是。如何重用联接线程 2 属性,使程序持续运行?

执行线程 2 一次后,线程 1 忽略我的 join 语句,只在 while 循环中轮询, 是唯一正在运行的线程。

请注意,在您的情况下,pthread_join(( 很可能会失败,并显示错误 2. 时间。检查其返回值。

但是,由于线程 2 已退出,因此没有线程可等待。您必须重新启动线程 2。那是:

thread 1 {
  while true
    if(some condition)
      join thread 2 
      // Use the returned value from thread 2
      create thread 2;
}