示例1:
如果不用锁,会发生什么呢?
参考:C++11多线程锁(入门)_c++线程加锁-优快云博客
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
qDebug()<<"main:"<<QThread::currentThreadId();
connect(this,SIGNAL(destroyed()),this,SLOT(quitThreadSlot()));
t=new try_thread(this);
t->start();
t1=new try_thread(this);
t1->start();
}
Widget::~Widget()
{
delete ui;
}
void Widget::quitThreadSlot()
{
t->quit();
t->wait();
t1->quit();
t1->wait();
}
为什么要quit() :回头看[2024/8/28]这段代码,发现不需要执行quit()函数
因为如果线程没有开启事件循环的话,该函数不起作用。
int counter=0;
try_thread::try_thread(QObject *parent) : QThread(parent)
{
}
void try_thread::run()
{
for(int i=0;i<100;i++)
{
counter++;
this->msleep(10); //每10ms休眠1次
qDebug()<<"son:"<<QThread::currentThreadId()<<" "<<counter;
}
}
输出结果:
main: 0x3948
son: 0x3ebc 2
son: 0x2140 2
son: 0x2140 4
son: 0x3ebc 4
son: 0x2140 6
son: 0x3ebc 6
son: 0x3ebc 8
son: 0x2140 8
son: 0x3ebc 10
son: 0x2140 10
son: 0x2140 12
son: 0x3ebc 12
son: 0x2140 14
son: 0x3ebc 14
son: 0x3ebc 16
son: 0x2140 16
son: 0x3ebc 18
son: 0x2140 18
s