I'm learning pthreads after learning about regular threads. Normally when we use a boolean thread object we declare it as a volatile object like this: volatile bool thread_lock;
. Do we need to do this on pthread objects as well, specifically on pthread_mutex_t
when needed or does it handle it itself?
I've looked up into the pthread_mutex_t
declaration and found out that it does not have a volatile declaration.
Should it be volatile pthread_mutex_t my_obj;
or pthread_mutex_t my_obj;
CodePudding user response:
Normally when we use a boolean thread object we declare it as a volatile object like this:
volatile bool thread_lock;
This use of volatile
has never been standard. Some platforms added these semantics to volatile
as a regrettable and confusing extension.
More tedious details in another answer, but the short version is that you should never use volatile
for synchronization. It's neither necessary nor sufficient.
The POSIX threading library takes care of everything for you - if you needed to write volatile
to make it work, it would say that in its manpages and documentation. It doesn't, because you don't.
More portably, C has had its own standard concurrency support since 2011, and it's perfectly mature.