POSIX C Threads. Mutex example. Don't work as expected

Jacob Krieg picture Jacob Krieg · Apr 15, 2012 · Viewed 8.8k times · Source

I have a big problem, I can't figure out why mutexes in C don't work as I expect. This is my code:

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>

pthread_t mythread;
pthread_mutex_t mymutex;

void *anotherFunc(void*)
{
    pthread_mutex_lock(&mymutex);

    for(int i = 0; i < 100; i++)
        printf("anotherFunc\n");

    pthread_mutex_unlock(&mymutex);

    pthread_exit(NULL);
}

void *func(void*)
{
    pthread_mutex_lock(&mymutex);

    for(int i = 0; i < 100; i++)
        printf("func\n");

    pthread_mutex_unlock(&mymutex);

    pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
    pthread_mutex_init(&mymutex, NULL);

    pthread_create(&mythread, NULL, func, NULL);
    pthread_create(&mythread, NULL, anotherFunc, NULL);

    pthread_mutex_destroy(&mymutex);

    pthread_exit(NULL);
    return EXIT_SUCCESS;
}

What I expect to happen is the program to print first 100 "func" messages and then 100 "anotherFunc" messages. What I expect is execution to reach func and lock the mutex. When the execution reaches anotherFunc, I expect to wait until func unlocks the mutex. But I get interfered messages like

func func func anotherFunc anotherFunc anotherFunc func anotherFunc

I don't understand how this thing works. Please help!

Answer

cnicutar picture cnicutar · Apr 15, 2012
pthread_create(&mythread, NULL, func, NULL);
pthread_create(&mythread, NULL, anotherFunc, NULL);

pthread_mutex_destroy(&mymutex);

You're destroying the mutex before the threads are done with it, so all bets are off. You'll probably want to pthread_join the 2 threads before destroying it.