lundi 20 août 2018

C++ - Concurreny - How to avoid deadlock and reuse an Exchanger in below Example

Hello Stack Overflow Experts,

I am breaking my brains over this but still can't get it working. First the background. I implemented an Exchanger in C++ similar to Java SE provided an interface that helps exchange message between two threads. I implemented internally Exchanger using a CyclicBarrier with barrier limit of 2 because the Exchanger needs two threads. Now after a successful exchange has happened between two threads I want to reset the Exchanger as underneath CyclicBarrier needs a reset as the well.

Now only one thread needs to do this while ensuring that when reset is happening the other thread does not attempt to hit the exchanger exchange method.

Please look at the code: https://github.com/anandkulkarnisg/Exchanger/blob/master/Example2.cpp

specifically the below code snippet.

void testExchanger(const std::string& inputString,const bool& resetStatus)
{
    printOut("I am currently running from thread id =", ".The value i am having initially is = "+inputString, std::this_thread::get_id());
    std::string returnString;
    int i=0;

    // This has a dead lock situation! between lines of shared_lock and exclusive lock.

    while(i<1000)
    {
        try
        {
            std::shared_lock<std::shared_mutex> lock(sync_mutex);
            returnString = exchanger.exchange(inputString);
        }
        catch(const std::exception& e)
        {
            std::cout << e.what() << std::endl;
        }
        printOut("I am currently running from thread id =", ".The value i am having now is = " + returnString, std::this_thread::get_id());
        if(resetStatus)
        {
            std::unique_lock<std::shared_mutex> lock(sync_mutex);
            exchanger.reset();
            lock.unlock();
        }
        ++i;
    }
}

Aucun commentaire:

Enregistrer un commentaire