Thread-safe class

Hello everyone,

I have started to use C++, and I am stuck with an issue.

Can anyone explain what is a Thread-safe class, and what does it mean to write a thread-safe class to manage whatever an application needs to do ? for example, handle a queue/stack of objects.


Thanks in advance.
Thread safe meant it will work correctly if several threads will try to access it together.
FOr example following class is not thread safe
1
2
3
4
5
6
7
8
9
10
11
12
13
class NotSafe
{
public:
    NotSafe(){x = new int}
    void reallocate() 
    {
        delete x;
        x = new x;
    }
    int access() {return *x}
private:
    int* x;
};
If thread calls reallocate and after line 7 will be executed (deleting x) another thread will request access() function which will try to dereference invalid pointer. Which can lead to crash.

In C++ you usually uses locks and mutexes to handle such situations.
Concurrency is an advanced topic and I believe you should learn it not on forums but using some books.
Example of similar question with answer:
http://stackoverflow.com/questions/3482352/need-some-feedback-on-how-to-make-a-class-thread-safe
Thank you

can you please advice a C++ book which can be helpful like the Java Black Book ?
Topic archived. No new replies allowed.