initialization lock is very important. If you do not initialize your locks to the desired value, your code breaks. One way to initialize your lock is as follows:
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
You can also perform this task dynamically using the following code:
int rc = pthread_mutex_init(&lock, NULL); assert(rc == 0); // always check success!
In addition to initializing the lock, you should check the pthread_mutex_lock return code to see if it will work or not, as if it worked, several threads can enter the critical section. For this, you can use code similar to this that checks the pthread_mutex_lock return code:
// Use this to keep your code clean but check for failures // Only use if exiting program is OK upon failure void Pthread_mutex_lock(pthread_mutex_t *mutex) { int rc = pthread_mutex_lock(mutex); assert(rc == 0); }
source share