int
variable that holds balance. int
variable. int
pointer at any time and add some value. Is it thread safe to do this? Or I should use 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.