[英]C++ access to Int variable from two threads. Thread safe?
int
variable that holds balance. 有一个int
变量可以保持平衡。 int
variable. 许多线程引用此int
变量。 int
pointer at any time and add some value. 每个线程都执行其工作,并且可以随时访问int
指针并添加一些值。 Is it thread safe to do this? 这样做是线程安全的吗? Or I should use mutex lock
? 还是我应该使用mutex lock
?
Here is example (it works without any issues, just need to be sure if forever): 这是示例(它可以正常工作,只需要确定是否永远有效即可):
#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.