[英]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.