同步 2 个线程 c++ linux

syncronizing 2 threads c++ linux

我有这样的代码

#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 上获得相同的结果?

它与线程的调度有关。有时一个线程可能执行得更快。显然,线程 2 一次执行得更快,所以你得到 ... 1 2 2 ... 这没有错,因为互斥锁只确保一次只有一个线程打印计数,仅此而已。存在不确定性,例如线程何时休眠以及何时唤醒等。所有这些可能不会始终在两个线程中花费完全相同的时间。

为了让线程交替执行,需要不同的信号量安排。例如,假设有两个信号量,s1 和 s2。设 s1 和 s2 的初始值分别为 1 和 0。考虑以下伪代码:

// Thread 1:
P (s1) 
print number
V (s2)

// Thread 2:
P (s2)
print number
V (s1)