【发布时间】:2019-06-18 17:55:24
【问题描述】:
在此处找到代码:http://coliru.stacked-crooked.com/a/7942a18fe11ea544
我正在试验条件。等待没有超时,我发现自己陷入了僵局。我要做的事情的要点是坐在锁中,直到我确定我已经创建了一个新文件。我会设置一个标志并通知线程,然后(在我的真实程序中)将触发一个回调函数。在运行结束时,我想关闭所有线程。我将循环变量设置为 false,然后通知一个,我认为这会解除线程阻塞。我误认为这会忽略谓词评估的内容吗?
有人可以建议一个更好的线程布局来纠正死锁吗? 谢谢。
#include <iostream>
#include <string>
#include <thread>
#include <chrono>
#include <atomic>
#include <mutex>
#include <condition_variable>
using namespace std::chrono_literals;
std::atomic_bool new_file_created_{false};
std::atomic_bool run_data_logger_{false};
std::condition_variable file_monitor_condition_;
std::mutex file_monitor_mutex_;
std::thread test_thread_;
void file_monitor_thread_func()
{
using namespace std::chrono_literals;
while (run_data_logger_)
{
std::unique_lock<std::mutex> lock(file_monitor_mutex_);
file_monitor_condition_.wait(lock, [] { return new_file_created_.load(); });
if (new_file_created_)
{
std::cout<< "New File Created" << std::endl;
new_file_created_ = false;
//do some stuff
}
else
{}
}
}
void end_the_thread()
{
std::cout << "Ending the Thread" << std::endl;
run_data_logger_ = false;
file_monitor_condition_.notify_one();
if (test_thread_.joinable())
test_thread_.join();
std::cout << "Thread Ended" << std::endl;
}
void trigger_new_file()
{
new_file_created_ = true;
file_monitor_condition_.notify_one();
}
void start_the_thread()
{
run_data_logger_ = true;
test_thread_ = std::thread(file_monitor_thread_func);
trigger_new_file();
}
int main()
{
for (int j = 0; j<10; j++)
{
start_the_thread();
std::this_thread::sleep_for(500ms);
end_the_thread();
}
}
【问题讨论】:
-
您不能使用没有更改状态的条件和该状态的互斥锁。
标签: c++ multithreading mutex race-condition monitor