borune
borune

Reputation: 566

syncronizing 2 threads c++ linux

i have such code

#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

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.

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

Upvotes: 0

Views: 52

Answers (1)

kjohri
kjohri

Reputation: 1224

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.

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)

Upvotes: 1

Related Questions