3

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?

cong
  • 1,105
  • 1
  • 12
  • 29

1 Answers1

2

There are surely similar questions and answers here on SO, but I will provide a couple of info points here.

First, usually, the biggest cost of a mutex is if at least 2 threads are hammering the mutex hard. An uncontended mutex is not expensive, essentially it can be implemented in terms of an atomic flag.

An additional fact is that mutexes come with barriers to implement e.g. sequential consistency. Roughly, if another thread running on another CPU core reads data written by one thread in the critical section, that data must be published over the bus at mutex unlock to make sure the other processors/CPU cores' caches see the data.

Erik Alapää
  • 2,585
  • 1
  • 14
  • 25