IGHOR
IGHOR

Reputation: 710

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

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;
}

Upvotes: 1

Views: 1755

Answers (1)

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17415

No, it's not thread-safe and you should either use a lock or atomic operations.

Upvotes: 10

Related Questions