1
votes

I have my code below. It's a simple example of printing alternating numbers up to 2N, using 3 threads. One prints 0, one prints odd numbers, and one prints even. for example input of 2 outputs 0102 to the console. Currently the code works, however I have a question just for my understanding.

For example in the odd function, if I change

            while (!(print_zero == 0 && print_odd == 1)) {
            cv.wait(lck);
        }

to

            //doesnt work
        while (print_zero == 1 && print_odd == 0) {
            cv.wait(lck);
        }

I don't get consistent correct behavior anymore, instead sometimes it deadlocks, sometimes it prints in a funky order. But to me it seems like it should be the same, and that the logic is identical. Does anyone know why this is the case?

#include <condition_variable>
#include <mutex>
#include <iostream>
#include <atomic>

using namespace std;

class ZeroEvenOdd {
private:
    int n;
    mutex mtx;
    condition_variable cv;
    int print_zero, print_even, print_odd;

public:
    ZeroEvenOdd(int n) {
        this->n = n;
        print_zero = 1;
        print_even = 0;
        print_odd = 1;
    }

    void printNumber(int x) {
        cout << x << endl;
    }

    // printNumber(x) outputs "x", where x is an integer.
    void zero( ) {
        for (int p = 0; p < n; p++) {
            std::unique_lock<std::mutex> lck(mtx);

            while (print_zero == 0) {
                cv.wait(lck);
            }
            printNumber(0);
            print_zero = 0;
            cv.notify_all();

        }
    }

    void even( ) {
        //2
        for (int j = 2; j <= n; j += 2) {
            std::unique_lock<std::mutex> lck(mtx);

            while (!(print_zero == 0 && print_even == 1)) {
                cv.wait(lck);
            }
            printNumber(j);
            print_zero = 1;
            print_even = 0;
            print_odd = 1;
            cv.notify_all();
        }
    }

    void odd() {
        //3
        for (int i = 1; i <= n; i += 2) {
            std::unique_lock<std::mutex> lck(mtx);
            //doesnt work
            //while (print_zero == 1 && print_odd == 0) {
            //    cv.wait(lck);
            //}
            while (!(print_zero == 0 && print_odd == 1)) {
                cv.wait(lck);
            }
            printNumber(i);
            print_zero = 1;
            print_even = 1;
            print_odd = 0;
            cv.notify_all();
        }
    }
};

int main()
{
    std::cout << "Hello World!\n";
    ZeroEvenOdd object(10);
    std::thread t1(&ZeroEvenOdd::zero, &object);
    std::thread t3(&ZeroEvenOdd::odd, &object);
    std::thread t2(&ZeroEvenOdd::even, &object);


    t1.join();
    t2.join();
    t3.join();

    cout << "done" << endl;
}
De Morgan's laws: p and q is equivalent to not ((not p) or (not q)). Your two conditions are not equivalent in the first place. - ph3rin