【发布时间】:2016-03-17 20:06:33
【问题描述】:
我是多线程编程的新手,所以这个问题可能看起来有点傻,但我真的需要解决这个问题,这样我才能将它应用到我的项目中(这要复杂得多)。 下面是我的代码,我试图让 2 个线程(父线程和子线程)在它们执行时更新同一个共享定时器,并在定时器达到特定限制时停止。 但是当我编译并执行这段代码时,有两种不同的结果: 1. child 打印“由 child 在 200000 完成”但程序没有退出; 2.child打印“done by child at 200000”并退出后,parent继续执行,打印几十行“parent doing work”和“parent at 190000”,然后打印“done by parent at 200000”和程序正确退出。 我想要的行为是对于更新计时器的任何线程,达到限制并退出,另一个线程也应该停止执行并退出。我想我可能在这里遗漏了一些微不足道的东西,但我已经尝试以多种方式更改代码,但我尝试的任何方法似乎都不起作用。任何帮助将不胜感激:)
#include <iostream>
#include <unistd.h>
#include <mutex>
#include <time.h>
using namespace std;
mutex mtx;
int main () {
int rc;
volatile int done = 0;
clock_t start = clock();
volatile clock_t now;
rc = fork();
if (rc == 0) { //child
while (true) {
cout << "child doing work" << endl;
mtx.lock();
now = clock() - start;
if (done) {
mtx.unlock();
break;
}
if (now >= 200000 && !done) {
done = 1;
cout << "done by child at " << now << endl;
mtx.unlock();
break;
}
cout << "child at " << now << endl;
mtx.unlock();
}
_exit(0);
}
else { // parent
while (true) {
cout << "parent doing work" << endl;
mtx.lock();
now = clock() - start;
if (done) {
mtx.unlock();
break;
}
if (now >= 200000 && !done) {
done = 1;
cout << "done by parent at " << now << endl;
mtx.unlock();
break;
}
cout << "parent at " << now << endl;
mtx.unlock();
}
}
return 0;
}
【问题讨论】:
-
volatile没有做你认为它使用 std::atomic 的事情。而且你不是在测试线程而是进程 -fork在你的进程中创建一个新进程而不是一个新线程。 -
你没有两个线程,而是一个父进程和一个子进程(那是完全不同的)。
-
请停止使用
volatile。对于fork和进程,您可以阅读beej.us/guide/bgipc for IPC。 -
那些不是独立的线程,它们是独立的进程。
-
@LongLin 为什么不用
std::thread?
标签: c++ multithreading timer