- There is an
intvariable that holds balance. - Many threads reference this
intvariable. - Each thread does their job and can access to
intpointer 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;
}