I am writing a program in C and I have a function that calls multiple threads.
Those threads will run on a loop until a flag is set to off. That flag is just an int with the value of 0 or 1.
For performance reasons, I don't want to set up a mutex for reading this flag and I don't think I really need it because none of the threads is writing to that flag but I am not sure.
What is your input?
Note: The flag is being set to off by the main process/thread, before I call join_pthread
.
Do I need mutexes for read operation only?
No - but, your threads do not only read from the variable. There is one thread writing to it.
Without some kind of synchronization (making the variable atomic or by using a mutex) the program will have a data race. With that, your program has undefined behavior and could act very strangely. The reading threads may never see that the writing thread has written anything for example. Even if the program looks like it's working one day, the next day it may not. Avoid undefined behavior like the plague.