【发布时间】:2023-03-13 22:32:01
【问题描述】:
我有这样的代码
#include <iostream>
#include <thread>
#include <mutex>
#include <iostream>
#include <unistd.h>
using namespace std;
bool isRunning;
mutex locker;
void threadFunc(int num) {
while(isRunning) {
locker.lock();
cout << num << endl;
locker.unlock();
sleep(1);
}
}
int main(int argc, char *argv[])
{
isRunning = true;
thread thr1(threadFunc,1);
thread thr2(threadFunc,2);
cout << "Hello World!" << endl;
thr1.join();
thr2.join();
return 0;
}
运行此代码时,我正在等待输出如下:
1
2
1
2
1
2
1
2
...
但我不明白,而是得到这样的东西:
1
2
1
2
2 <--- why so?
1
2
1
如果我在 Windows 上运行此代码,将 #include <unistd.h> 替换为 #include <windows.h> 并将 sleep(1) 替换为 Sleep(1000),我得到的输出正是我想要的,即 1212121212。
那么为什么会这样,如何在linux上达到同样的效果呢?
【问题讨论】:
标签: linux multithreading mutex