Search code examples
cmultithreadingpthreadsmutexthread-synchronization

pthread synchronization using mutex


I was trying to create 2 threads and calling the same function which increments a counter "count" from a for loop. But every time I run this code the value of the counter is different. I try to use mutex to have synchronization between threads when they increment the global static variable "count" but still value is different.

static int  count;
pthread_mutex_t count_mutex;

 void increment()
 {
    pthread_mutex_lock(&count_mutex);
    count++;
    pthread_mutex_unlock(&count_mutex);
}

void *myThreadFun1(void *var)
{
    printf("Thread1\n");
    for(int i=0; i< 10000;i++)
    {
        increment();
    }
    return;
}

int main()
{
    pthread_t tid1;
    pthread_t tid2;
    pthread_create(&tid1, NULL, myThreadFun1, NULL);
    // sleep(1);
    pthread_create(&tid2, NULL, myThreadFun1, NULL);
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    printf("\n%d",count);
    exit(0);
}

Output is never 20000 if I don't sleep between threads.

In java there is "synchronized" keyword we can use, but how to achieve same in C ?


Solution

  • pthread_mutex_t requires initialization before use. It must start unlocked and unbound. There is a call, pthread_mutex_init(&theMutex) that can do this, or a predefined value can be assigned for static init: PTHREAD_MUTEX_INITIALIZER