如何保护QThread函数,使其在完成之前的工作之前不会被再次调用
How can I protect a QThread function so it will not be called again until finished its previous work?
我使用一个QThread,在它的run
方法中,我有一个计时器调用一个函数,该函数执行一些需要一些时间的重操作。通常大于触发定时器的时间间隔(但不总是)。
我需要的是保护这个方法,这样只有当它完成之前的工作时才能调用它。
代码如下:
NotificationThread::NotificationThread(QObject *parent)
: QThread(parent),
bWorking(false),
m_timerInterval(0)
{
}
NotificationThread::~NotificationThread()
{
;
}
void NotificationThread::fire()
{
if (!bWorking)
{
m_mutex.lock(); // <-- This is not protection the GetUpdateTime method from invoking over and over.
bWorking = true;
int size = groupsMarkedForUpdate.size();
if (MyApp::getInstance()->GetUpdateTime(batchVectorResult))
{
bWorking = false;
emit UpdateNotifications();
}
m_mutex.unlock();
}
}
void NotificationThread::run()
{
m_NotificationTimer = new QTimer();
connect(m_NotificationTimer,
SIGNAL(timeout()),
this,
SLOT(fire(),
Qt::DirectConnection));
int interval = val.toInt();
m_NotificationTimer->setInterval(3000);
m_NotificationTimer->start();
QThread::exec();
}
// This method is invoked from the main class
void NotificationThread::Execute(const QStringList batchReqList)
{
m_batchReqList = batchReqList;
start();
}
你总是可以有一个线程,需要运行的方法连接到一个onDone信号,提醒所有订阅者它已经完成。这样就不会遇到与双锁检查和内存重排序相关的问题。维护每个线程的运行状态
我假设您想保护您的线程不受其他线程的调用。我说的对吗?
这就是QMutex的作用。QMutex为您提供了一个接口来"锁定"线程,直到它被"解锁",从而序列化对线程的访问。您可以选择解锁线程,直到它完成它的工作。但使用它的风险由你自己承担。如果使用不当,QMutex也会出现问题。关于这方面的更多信息,请参考文档。
但是有更多的方法来解决你的问题,比如,@Beached建议一个更简单的方法来解决问题;QThread的实例在完成后会发出一个信号。或者更好的是,在你的线程中做一个bool isDone
,如果它完成了,那么它就是true
,或者如果它没有完成,它就是false
。如果它是true
,那么调用该方法是安全的。但是请确保不要在拥有它的线程之外操作isDone
。我建议你只在QThread中操作isDone
。
bWorking
的第二个建议。
相关文章:
- 即使没有调用这个递归函数,它是如何工作的?
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 推理类型如何工作"auto"和按引用调用?
- 以下代码如何工作以每次为唯一调用堆栈唯一实例化模板函数?
- 递归函数调用在后台工作
- std::async 如何工作:为什么它会调用这么多次复制/移动?
- QLibrary 函数在第一次调用时工作缓慢
- 工作线程一直在等待,condition_variable甚至调用了notify_all
- 虚拟基类在内部如何工作?编译器如何解析对基方法的调用?
- 在新作用域中使用unique_lock是否等效于在使用共享资源的工作结束时解锁调用
- 从Excel VBA调用C++DLL只能从Visual Studio中的调试实例工作
- 异步操作的 Asio 处理程序在其同步对应项正常工作时不会调用
- 如何使功能"run"工作。程序在调用运行时退出
- 当在函数调用中递增值时,程序正常工作,但是如果我们在单独的行中增加值而不是呼叫函数,则会出现错误.为什么
- 在线程中调用线程会给我带来错误,如果我只调用该函数,则可以正常工作
- boost::asio 使用 post() 时没有调用处理程序,当直接调用函数时有效(io_context有工作)
- 为什么用未申报的变量工作调用函子
- 引用调用在 c++ 中如何工作?
- winsock连接调用崩溃如果多个线程运行,则在一个线程中正常工作
- C Google Mock -Expect_Call() - 期望在不直接调用时无法正常工作