【问题标题】:POSIX pthread using same thread multiple timesPOSIX pthread 多次使用同一个线程
【发布时间】:2013-10-08 12:21:39
【问题描述】:

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

我的程序中有两个线程。线程运行得很好,但是导致问题的是线程的重用。伪代码如下:

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 循环中轮询,是唯一运行的线程。

所以我的问题是。如何重用join thread 2属性,让程序连续运行?

【问题讨论】:

  • 你想重新开始踩2,还是想重复使用它的回报?如果是后者,那么只需保存它,不要调用join。如果是前者,则重置条件并重新启动线程。
  • 是前者。线程 2 更改了一个变量,该变量在两个线程之间共享。我想重用线程 2,所以变量有正确的语句,供线程 1 使用。那么问题来了,我该如何重启他的线程呢?

标签: c++ multithreading pthreads posix


【解决方案1】:

线程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;
}

【讨论】:

  • 我试图这样做,但是,它会导致我的程序崩溃。第二个创建方法应该与主创建方法有什么不同吗?
  • @HansPeterson 如果它崩溃了,那么您可能需要在调试器中运行以帮助您找出它崩溃的原因。可能是您忘记重置某些状态?
  • 谢谢 :) 现在可以了。我不得不重新创建我交给 pthread_create 方法的变量。可能是导致崩溃的空指针。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-04
  • 2012-01-19
  • 1970-01-01
  • 2011-10-01
  • 2013-06-04
  • 2014-03-18
  • 1970-01-01
相关资源
最近更新 更多