问题描述
我对线程处理不是很糟糕,我需要帮助,
我有一个带有进度条的gtkmm窗口,任务是在后台执行多个Shell脚本或Shell命令,并相应地更新进度条。我有一个
button->clicked_signal() {
thread( [this] { worker->start() } );
}
worker->start() {
{
lock_guard(mutex); // as per i know to safely handle variables
progress = 0.0
}
caller->notify(); // i found it on documentation that its for sending signal to window to refresh
int ret = WEXITSTATUS(system("./my_shell_script with-args"));
{
lock_guard(mutex);
progress = 0.4;
}
caller->notify(); // Simmilary i am handling more scripts
}
问题是“完成”窗口处于冻结状态,直到过程完成。它仅发生在system()上; ,如果我使用loop()或其他函数,它将不会冻结。
我尝试了其他事情。
worker->executor() {
int ret = WEXITSTATUS(system("./my_shell_script with-args"));
{
lock_guard(mutex);
progress = 0.4;
}
// other executions
}
worker->start() {
thread th1(&worker::executor,this);
while(true) {
caller->notify();
if (stop) break;
this_thread::sleep_for(chrono::milliseconds(120));
}
th1.join();
caller->notify();
}
但仍在冻结。我在穿线方面很不好,
完整代码可在https://github.com/itsManjeet/opportunity.git分支(0.6.0)
获得他们是做这件事的更好的方法
解决方法
除主线程外,您无法从任何线程进行GUI更改或使用任何其他GTK函数。例如,如果需要更改进度条,则必须发信号通知主线程执行此操作,而不是尝试从辅助线程进行更改。您可以为此使用Glib::Dispatcher
。