I was wondering how much overhead will pthread_mutex_lock and pthread_mutex_unlock cause if it is not a multi-thread context, so I wrote a demo:
#include <pthread.h>
#include <stdio.h>
#include <time.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
#define LOOP_COUNT 1000000000
int main(int argc, char* argv[])
{
time_t cur_time = time(NULL);
double d = 0.0;
printf("%s", asctime(localtime(&cur_time)));
for (int i = 0; i < LOOP_COUNT; ++i) {
pthread_mutex_lock(&mutex);
d += 0.1;
pthread_mutex_unlock(&mutex);
}
cur_time = time(NULL);
printf("%s", asctime(localtime(&cur_time)));
d = 0.0;
for (int i = 0; i < LOOP_COUNT; ++i) {
d += 0.1;
}
cur_time = time(NULL);
printf("%s", asctime(localtime(&cur_time)));
return 0;
}
The output is:
Wed Mar 21 10:58:25 2018
Wed Mar 21 10:58:41 2018
Wed Mar 21 10:58:43 2018
So, does the overhead really exist? If it does, what do pthread_mutex_lock and pthread_mutex_unlock realy do so that cause the overhead?