简体   繁体   中英

C++ access to Int variable from two threads. Thread safe?

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM