Is there anything wrong in following source code if I don't use mutex?
bool bStop = false;
void thread1_fun()
{
while (!bStop)
{
doSomething();
}
}
void thread2_fun()
{
bStop = true;
}
It's more of a C question then a Rust question. But, no, it's not safe. You should use atomics or mutexes for synchronization.
It depends. The C++ language says nothing about threads or atomicity. But on most modern CPU's, reading an integer is an atomic operation, which means that you will always read a consistent value, even without a mutex.
None of these are thread-safe. The thread that calls the getter will always read a stale value. How stale it is depends on the processor and the optimizer.
Updating a bool is always thread safe, if you never read from it. And if you do read from it, then the answer depends on when you read from it, and what that read signifies. On some CPUs, but not all, writes to an object of type bool will be atomic. x86 CPUs will generally make it atomic, but others might not.
It is undefined behaviour to write to an object in one thread while another thread accesses the object at all.
Unless you specifically inform the compiler that there should be a fence, such as the use of std::atomic
, std::mutex
et al, all bets are off.
The compiler is within its rights to re-write the code as this:
bool bStop = false;
void thread1_fun()
{
const bool stopped = bStop;
// compiler reasons: "because there is no fence, the variable clearly cannot
// have changed to true, since no-other thread will modify it, since
// to modify it without a fence would be UB."
while (!stopped)
{
doSomething();
}
}
void thread2_fun()
{
// this happens in my thread's view of the world,
// but no other thread need see it.
bStop = true;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With