gpt4 book ai didi

c++ - 条件变量不起作用,但在添加 std::cout 后,它起作用了

转载 作者:行者123 更新时间:2023-11-28 02:25:27 28 4
gpt4 key购买 nike

我的项目由两个线程组成:一个主线程和另一个处理另一个窗口内容的线程。因此,当主线程想要请求另一个窗口更新自身时,它调用如下绘制函数:

void SubApplicationManager::draw() {

// Zero number of applications which has finished the draw counter
{
boost::lock_guard<boost::mutex> lock(SubApplication::draw_mutex);
SubApplication::num_draws = 0;
}

// Draw the sub applications.
for (size_t i = 0; i < m_subApplications.size(); i++)
m_subApplications[i].signal_draw();

// Wait until all the sub applications finish drawing.
while (true){
boost::lock_guard<boost::mutex> lock(SubApplication::draw_mutex);
std::cout << SubApplication::num_draws << std::endl;
if (SubApplication::num_draws >= m_subApplications.size()) break;
}

}

draw 函数只是向另一个线程发送信号,表明已收到新任务。

void SubApplication::signal_draw() {

task = TASK::TASK_DRAW;
{
boost::lock_guard<boost::mutex> lock(task_received_mutex);
task_received = true;
}
task_start_condition.notify_all();

}

其他线程的主体如下。它等待任务到达,然后开始处理:

void SubApplication::thread() {

clock_t start_time, last_update;
start_time = last_update = clock();

//! Creates the Sub Application
init();

while (!done) // Loop That Runs While done=FALSE
{
// Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene()
if (active) // Program Active?
{
// Wait here, until a update/draw command is received.
boost::unique_lock<boost::mutex> start_lock(task_start_mutex);
while (!task_received){
task_start_condition.wait(start_lock);
}

// Task received is set to false, for next loop.
{
boost::lock_guard<boost::mutex> lock(task_received_mutex);
task_received = false;
}

clock_t frame_start_time = clock();

switch (task){
case TASK_UPDATE:
update();
break;

case TASK_DRAW:
draw();
swapBuffers();
break;

case TASK_CREATE:
create();
break;

default:
break;
}

clock_t frame_end_time = clock();
double task_time = static_cast<float>(frame_end_time - frame_start_time) / CLOCKS_PER_SEC;

}
}
}

问题是,如果我按原样运行代码,它永远不会用 task = TASK::TASK_DRAW; 运行另一个线程但如果我添加 std::cout << "Draw\n";SubApplication::draw()的开头,它将正常工作。我正在寻找它发生的原因以及通常的修复方法是什么?

最佳答案

boost::lock_guard<boost::mutex> lock(task_received_mutex);
task_received = true;

好的,task_received_mutex 保护 task_received

    boost::unique_lock<boost::mutex> start_lock(task_start_mutex);
while (!task_received){
task_start_condition.wait(start_lock);
}

糟糕,我们正在读取 task_received 而没有持有保护它的互斥量。是什么阻止了一个线程读取 task_received 而另一个线程正在修改它的竞争?这可能会立即导致死锁。

此外,您的代码声称“等待所有子应用程序完成绘制”,但没有调用任何等待函数。所以它实际上是旋转而不是等待,这很糟糕。

关于c++ - 条件变量不起作用,但在添加 std::cout 后,它起作用了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30839734/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com