I am getting TLE on a Multithreading problem Semaphore

  c++, multithreading, semaphore

I was trying to attempt this question on Leetcode and got a TLE.
There are 3 functions printZero, printEven, printOdd, which are given to 3 different threads.
printZero only should print 0.
printOdd should print 1, 3, 5, 7, …
printEven should print 2, 4, 6, 8, …
We should manage the code in such a way the output must be 0102030405…
printNumber(int n) here prints n.
I saw the discussion forum and tried to post a comment on Leetcode, but no response.
Can someone help me with this?

Below is my code:

#include "semaphore.h"
class ZeroEvenOdd {
private:
    int n;
    int cur;
    sem_t semObjZero;
    sem_t semObjEven;
    sem_t semObjOdd;
    int next;
public:
    ZeroEvenOdd(int n) {
        this->n = n;
        sem_init(&semObjZero, 0, 1);
        sem_init(&semObjEven, 0, 0);
        sem_init(&semObjOdd, 0, 0);
        cur = 1;
        next = 1;
    }

    // printNumber(x) outputs "x", where x is an integer.
    void zero(function<void(int)> printNumber) {
        sem_wait(&semObjZero);
        printNumber(0);
        if (next == 1) {
            sem_post(&semObjOdd);
            next = 2;
        }
        else {
            sem_post(&semObjEven);
            next = 1;
        }
    }

    void even(function<void(int)> printNumber) {
        sem_wait(&semObjEven);
        printNumber(cur);
        cur++;
        sem_post(&semObjZero);
    }

    void odd(function<void(int)> printNumber) {
        sem_wait(&semObjOdd);
        printNumber(cur);
        cur++;
        sem_post(&semObjZero);
    }
};

Thanks in advance

Source: Windows Questions C++

LEAVE A COMMENT