[英]C++ access to Int variable from two threads. Thread safe?
int
變量可以保持平衡。 int
變量。 int
指針並添加一些值。 這樣做是線程安全的嗎? 還是我應該使用mutex lock
?
這是示例(它可以正常工作,只需要確定是否永遠有效即可):
#include <QCoreApplication>
#include <QThread>
#include <QDebug>
#include <QTimer>
int someInt=0;
class MyThread : public QThread
{
public:
MyThread(){start();}
void run()
{
for(int n=0;n<1000;n++)someInt-=1;
for(int n=0;n<1000;n++)someInt+=2;
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qDebug()<<"someInt="<<someInt;
QTimer::singleShot(5000,&a,SLOT(quit()));
MyThread thread1;
MyThread thread2;
a.exec();
//There always 2000 output, and there is no issue,
//just need to be sure if forever.
qDebug()<<"someInt="<<someInt;
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.