Thread Implementation

Mar 1, 2013 at 1:44am
I want to create two threads which will be calling even and odd functions where even function should print even number and odd function should print odd number.
Can it be possible with the help of condition variable?
please explain it with the code itself in both the cases i.e. two separate function and with the help of condition variable.
Mar 1, 2013 at 2:33am
Are you talking about something like this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <condition_variable>
#include <thread>

std::condition_variable cv;
std::mutex cv_m;
int n = 0;
const int LIM = 15;
void print_odds()
{
    while(n < LIM)
    {
        std::unique_lock<std::mutex> lk(cv_m);
        cv.wait(lk, [](){return n%2 == 1;});
        std::cout << "odd: " << n++ << '\n';
        cv.notify_one();
    }
}

void print_evens()
{
    while(n < LIM)
    {
        std::unique_lock<std::mutex> lk(cv_m);
        cv.wait(lk, [](){return n%2 == 0;});
        std::cout << "even: " << n++ << '\n';
        cv.notify_one();
    }
}

int main()
{
    std::thread t1(print_odds);
    std::thread t2(print_evens);
    t1.join();
    t2.join();
}

online demo: http://liveworkspace.org/code/2wWbQg
Mar 2, 2013 at 12:30am
I tried to run the mentioned code above but I get lots of compilation issues. It could be because of different compiler. Could you please explain what all lines are about? If possible Can I get a code for unix environment? Actually I am trying to understand the multithreading in C++ as getting lots of questions in interview.
Mar 2, 2013 at 12:38am
The above code will work in any environment (Windows, *nix, Mac) assuming you have a compiler that supports C++11. Try compiling for C++11
Mar 2, 2013 at 2:45am
compile above code with -std=c++0x option.
g++ AboveProgram.cpp -std=c++0x

If you are using g++ 4.7 or later, you can use -std=c++11 opstion.
Mar 2, 2013 at 6:26am
also needs -pthread with gcc (or you could use boost if you don't have a C++ compiler that supports threads)
Mar 2, 2013 at 8:03am
also needs -pthread with gcc (or you could use boost if you don't have a C++ compiler that supports threads)

Yes, Thanks, I forgot that.
Topic archived. No new replies allowed.