Reputation: 21
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 ();
Upvotes: 0
Views: 1075
Reputation: 58868
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 a pthread_mutex_t
object does not create a mutex. You have to call pthread_mutex_init
to create the mutex. Likewise you have to call pthread_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.
pthread_mutex_t * mutex1 = new pthread_mutex_t; // () not needed
// you created a pthread_mutex_t object, but didn't initialize it.
// You created it with new, so destroy it with delete:
delete mutex1;
pthread_mutex_t * mutex1 = new pthread_mutex_t; // () not needed
// you created a pthread_mutex_t object
pthread_mutex_init(&mutex1, nullptr); // can check return value for errors
// and used that space to store whatever data a mutex has in it (perhaps pthread_mutex_init allocates other memory)
// Reverse pthread_mutex_init with pthread_mutex_destroy:
pthread_mutex_destroy(&mutex1); // can check return value for errors
// You created it with new, so destroy it with delete:
delete mutex1;
std::mutex * mutex3 = new std::mutex; // () not needed
// You created it with new, so destroy it with delete
delete mutex3;
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:
std::mutex mutex4;
// automatically destroyed when it goes out of scope
and the C version:
pthread_mutex_t mutex5;
pthread_mutex_init(&mutex5, nullptr); // can check return value for errors
// Reverse pthread_mutex_init with pthread_mutex_destroy:
pthread_mutex_destroy(&mutex5); // can check return value for errors
// Variable is destroyed when it goes out of scope.
// Of course you can reuse the same variable for a new mutex by calling init again
// and destroy when you are done
Upvotes: 1