Moh*_*ani 1 c++ cpu qt multithreading stdthread
我有一个功能.在我的函数中有一个c ++线程和一个Qtimer.通过c ++线程我收到ARP回复数据包,并通过QTimer我发送ARP请求数据包.
简化结构:
int foo()
{
... some codes ...
QTimer::singleShot(1000, this, SLOT(beginSending()));
std::thread tCapture(Capture);
tCapture.join();
return 0;
}
void Capture()
{
while ( ! finishCapturing )
{
do sth
}
}
Run Code Online (Sandbox Code Playgroud)
在tCapture线程中我有一个使用所有CPU的while循环并且Qtimer不起作用!
我使用.join()是因为我想等待线程完成.
当我finishCapturing在Qtimer插槽中设置标志时,线程将完成.
上面的代码无法正常工作,因为c ++线程占用了所有CPU!
问题是什么?
非常感谢.雅阿里
问题是在创建它们之后立即加入线程,这会阻塞GUI线程以及该线程上的QTimer所有插槽.
你应该做的是signal在捕获完成时发出一个;
public void beginSending(){
//do sending and capture
finishCapturing =true;
emit finshedCapture();
}
Run Code Online (Sandbox Code Playgroud)
如果需要,你可以将while的主体放在一个槽中,并使用QTimer重复调用,超时为0(这意味着将尽可能多地调用槽).
然后你可以将finshedCapture()信号连接到stop()QTimer 的插槽
int foo()
{
... some codes ...
QTimer::singleShot(1000, this, SLOT(beginSending()));
QTimer* timer = new QTimer(this);
connect(timer, signal(timeout()), this, slot(Capture()));
connect(this, signal(finshedCapture()), timer, slot(stop()));
connect(this, signal(finshedCapture()), timer, slot(deleteLater()));//cleaup when done
timer->setTimeout(0);
timer->setSingleShot(false);
timer->start();
return 0;
}
void Capture()
{
//no while because the timer will call it as needed
//do sth
}
Run Code Online (Sandbox Code Playgroud)