同步2个线程C ++ Linux [英] syncronizing 2 threads c++ linux

查看:62
本文介绍了同步2个线程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;
}

在运行此代码时,我正在等待获得如下输出:

when running this code i'm waiting to get output like:

1
2
1
2
1
2
1
2
...

但是我不明白,反而得到这样的东西:

but i dont't get that and get something like this instead:

1
2
1
2
2  <--- why so?
1
2
1

,如果我在Windows上运行此代码,将#include <unistd.h>替换为#include <windows.h>,将sleep(1)替换为Sleep(1000),则得到的输出正是我想要的,即1212121212.​​

and if i run this code on Windows with replacing #include <unistd.h> to #include <windows.h> and sleep(1) to Sleep(1000) the output i get is exactly what i want, i.e. 1212121212.

那么为什么这样以及如何在linux上达到相同的结果呢?

So why is so and how to achieve the same result on linux?

推荐答案

它与线程的调度有关.有时一个线程可能执行得更快.显然,线程2执行一次更快,因此您得到... 1 2 2 ...没什么错,因为互斥锁只能确保一次仅打印一个线程,而仅此而已.存在不确定性,例如何时线程将进入睡眠状态以及何时将其唤醒等.在两个线程中,所有时间可能并不一定完全相同.

It pertains to the scheduling of threads. Sometime one thread may be executing faster. Apparently, thread 2 is executing faster once and so you are getting ... 1 2 2 ... Nothing wrong with that because mutex is only ensuring that only one thread is printing count at a time and nothing more. There are uncertainties like when a thread is going to sleep and when it is woken up, etc. All this may not be taking exactly the same time in the two threads all the time.

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

For having the threads execute alternately, a different semaphore arrangement is needed. For example, let there be two semaphores, s1 and s2. Let the initial values of s1 and s2 be 1 and zero respectively. Consider the following pseudo code:

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

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

这篇关于同步2个线程C ++ Linux的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆