What is the difference between std::mutex and pthread_mutex_t in CPP?
What is the correct way to destroy each one of the mutex types when they are dynamically allocated as follows:
pthread_mutex_t * mutex1 = new pthread_mutex_t();
std::mutex * mutex2 = new std::mutex ();
The difference is that they are from different libraries. They are both mutexes (mutices?).
pthread_mutex
is from a library designed for C, so it does not use constructors or destructors. Simply creating apthread_mutex_t
object does not create a mutex. You have to callpthread_mutex_init
to create the mutex. Likewise you have to callpthread_mutex_destroy
to destroy it, because it has no destructor which does this.std::mutex
is designed for C++ so of course the object itself always acts as a mutex, with no need for separate function calls.However, you don't need to allocate everything with
new
. C++ isn't Java. If you want an object, then in the vast majority of cases you can just have one:and the C version: