【发布时间】: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