Hi
I am having two threads in my program. First thread (lets name Thread A) increments the value of global variable count(=0,1,...) and the second thread (say Thread B) displays the global variable count.
I used mutex and it appeared slower than without mutex. My question is as thread A modifies the value of count, is it ok if thread B reads count i.e. is this operation thread safe or do I need to use mutex.
Note: Thread B does not modify count. It only displays count.
I got count being incremented by one in both cases but as it is a high value not sure if in between there can be errors.
Yes, the mutex will make it slower but if you want the program to work properly you need to use it. To make it run as fast as possible you should try to minimize the time the mutex is locked. The printing thread doesn't need to hold the lock while printing. It only need to lock the mutex while reading the count variable. It could copy it to a local variable, then release the lock and then print the local variable.
I used mutex and it appeared slower than without mutex
Yes, it will be slower. Locking mutexes is slow -- they require the thread to basically stop and interrupt its pipeline. It's quite a significant performance hit. (This is why "multithreading" does not mean "faster" -- in many cases, it can be slower than just doing all the work in 1 thread)
The difference, though, is that using mutexes allow this to actually work. Not using them will get you race conditions and undefined behavior -- so you need them.
Or you can use some other memory locking mechanism, like atomic variables. And in fact... an atomic might be faster, and it is safe.
My question is as thread A modifies the value of count, is it ok if thread B reads count i.e. is this operation thread safe or do I need to use mutex.
No. It is not safe. It is a race condition.
The only way it's safe to access the same var across multiple threads simultaneously is if ALL threads are reading it. If any thread is writing... then accesses must be guarded.