dimanche 1 mai 2016

Print even and odd from different threads using condition variable

I am trying to print like 1,2,3,4,5,6,7,..... but even and odd numbers from two different threads. Also I want to make this program using condition variables. I have created the following program, it just prints the odd parts and hangs up (may be dead lock..I do not know). Please tell me what is the problem in my implementation.

#include<iostream>
#include<thread>
#include<mutex>
#include<condition_variable>
#define MAX 25
using namespace std;

mutex mu;
condition_variable cv;

void printodd()
{
    for (size_t i = 0; i < MAX; i++)
    {
        if (i % 2 != 0)
        {
            unique_lock<mutex> locker(mu);
            cout <<"Odd : "<< i << endl;
            locker.unlock();
            cv.notify_one();
        }
    }
}

void printeven()
{
    for (size_t i = 0; i < MAX; i++)
    {
        if (i % 2 == 0)
        {
            unique_lock<mutex> locker(mu);
            cv.wait(locker);
            cout <<"Even : "<< i << endl;
            locker.unlock();
        }
    }
}

int main()
{
    thread th1(printodd);
    thread th2(printeven);
    th1.join();
    th2.join();
    getchar();
}

Aucun commentaire:

Enregistrer un commentaire