Hello Stack溢出专家,
我为此不知所措,但仍然无法正常工作。首先是背景。我用类似于Java SE的C ++实现了一个Exchanger,它提供了一个有助于在两个线程之间交换消息的接口。 我使用CyclicBarrier内部实现了Exchanger,其屏障限制为2,因为Exchanger需要两个线程。现在,在两个线程之间成功进行交换之后,我想重置Exchanger,因为CyclicBarrier下方也需要重置。
现在,只有一个线程需要执行此操作,同时确保在发生重置时另一线程不会尝试使用交换器交换方法。
请查看代码:https://github.com/anandkulkarnisg/Exchanger/blob/master/Example2.cpp
特别是下面的代码段。
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;
}
}