mercredi 28 novembre 2018

how to make a thread wait on another thread called by itself

I am quite new to multithreading and c++11 thread libraries. I have one scenario and would appreciate your way forward with it.

I have 2 threads (say "thread1" and "thread2") such that, "thread1" calls "thread2" and it should wait on some condition until either it is fulfilled by "thread2" or a specific time has elapsed.

Couple of things are worth noting here in this context. Firstly, it's always "thread1" that calls and waits on "thread2" upon some condition or time-limit. Secondly, "thread2" never ever calls "thread1" at any point.

I tried a solution something like below:

bool condition = false;
std::mutex mtx;
std::condition_variable cv;

void thread1()
{
    std::string str = "string";
    std::unique_lock<std::mutex> lck(mtx);
    thread2(str);

    while(!condition)
    {
        cv.wait(lck);   // or let's say 60 seconds elapsed
    }

    std::cout << "condition reached" << std::endl;
}

void thread2(const std::string& str)
{
    calls_some_other_function();
    std::unique_lock<std::mutex> lck(mtx);
    condition = true;
    cv.notify_one();
}

Now, is this a correct implementation? The doubt I have with this implementation is that how to ensure that "thread2" always returns after "thread1" starts to wait on it, or else it will either keep waiting forever or come out of the timer (60 seconds, let's say) even though the condition is satisfying?.

Please help here.

Aucun commentaire:

Enregistrer un commentaire