1
  • 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;
}
7
  • Give a short code sample (not the complete code), that shows what you are trying to do. Commented May 28, 2014 at 17:49
  • Read the info page for multithreading: stackoverflow.com/tags/multithreading/info Commented May 28, 2014 at 17:51
  • Thank you. I'll read it and try to make some code for example. Commented May 28, 2014 at 17:54
  • I have added code, please look. Commented May 28, 2014 at 18:20
  • 1
    Thanks. I'll use std::atomic<quint64> and std::atomic<double>. Looks like it works good only for "+=", "-=" etc. operators, but it useles if use someInt=someInt+1. And std::atomic<double> does not have this operators. But I know direction. Thanks for answers! Commented May 28, 2014 at 22:54

1 Answer 1

10

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

Sign up to request clarification or add additional context in comments.

9 Comments

Is lock or atomic ooperations faster?
@IGHOR: No simple answer. It may be faster to sum up the totals only in the end, and keep per-thread partial sums.
It not possible to keep peer partial sums, because each thread should get access to this int realtime.
The variable doesn't influence in any way how the two threads behave, so there is no reason not to update it only once. Unless of course there is a requirement that you haven't mentioned yet.
Go with atomic. If you don't use c++11, gcc implements them anyway with some special functions.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.