【问题标题】:syncronizing 2 threads c++ linux同步2个线程c ++ linux
【发布时间】: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 &lt;unistd.h&gt; 替换为 #include &lt;windows.h&gt; 并将 sleep(1) 替换为 Sleep(1000),我得到的输出正是我想要的,即 1212121212。​​

那么为什么会这样,如何在linux上达到同样的效果呢?

【问题讨论】:

    标签: linux multithreading mutex


    【解决方案1】:

    它与线程的调度有关。有时一个线程可能执行得更快。显然,线程 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)
    

    【讨论】:

    • 好的,很明显,但是如何从这些线程中实现连续打印呢?应该使用什么同步机制?
    猜你喜欢
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    相关资源
    最近更新 更多