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.
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 = newint}
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.