POSIX C Threads. Mutex example. It does not work properly

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!

+8
c multithreading mutex multitasking
source share
2 answers
 pthread_create(&mythread, NULL, func, NULL); pthread_create(&mythread, NULL, anotherFunc, NULL); pthread_mutex_destroy(&mymutex); 

You destroy the mutex before the threads execute with it, so all bets are disabled. You probably want pthread_join 2 threads before you destroy it.

+16
source share

I got some errors in comiplation

  • I cannot declare int i in a loop

  • The arg argument name is used as the argument for the "func" and "anotherFunc" threads

I used pthread_join before , destroying the mutex.

Thus, I destroy my mutex "mymutex" after both the "func" and "anotherFunc" threads have completed execution

Also, each thread now has its own thread id "mythread1" and "mythread2" , so I can use the pthread_join () function for each thread

 #include <stdlib.h> #include <stdio.h> #include <pthread.h> pthread_t mythread1, mythread2; pthread_mutex_t mymutex; void *anotherFunc(void *arg) { pthread_mutex_lock(&mymutex); int i; for(i = 0; i < 100; i++) printf("anotherFunc\n"); pthread_mutex_unlock(&mymutex); pthread_exit(NULL); } void *func(void *arg) { pthread_mutex_lock(&mymutex); int i; for(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(&mythread1, NULL, func, NULL); pthread_create(&mythread2, NULL, anotherFunc, NULL); pthread_join(mythread1, NULL); pthread_join(mythread2, NULL); pthread_mutex_destroy(&mymutex); return EXIT_SUCCESS; } 
+2
source share

All Articles