I have a big problem, I canβt understand why the mutexes in C do not 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; }
It is expected that the program will print the first 100 messages "func", and then 100 messages "anotherFunc". I expect this to be done to achieve func and lock the mutex. When execution reaches anotherFunc, I wait until func unlocks the mutex. But I get interferences like
Funk FUNC FUNC anotherFunc anotherFunc anotherFunc FUNC anotherFunc
I do not understand how this works. Please, help!
c multithreading mutex multitasking
Jacob Krieg
source share