pthread_mutex_lock renvoie 22 en C

J’apprends à utiliser Pthread en C. J’ai essayé d’utiliser pthread_mutex_lock . Il est supposé renvoyer 0 lorsque le locking est réussi. Mais mon programme retourne toujours 22 – argument invalide.

Le code est le suivant:

pthread_mutex_lock est utilisé dans work_function

 #include  #include  #include  #include  #define N 2 void *work_function(void *param); int count=0; pthread_mutex_t mut; int main(int args, char **argv) { pthread_t tid[N]; long int iterations = atoi(argv[1]); pthread_create(&tid[0], NULL, work_function, (void *) iterations); pthread_create(&tid[1], NULL, work_function, (void *) iterations); pthread_join(tid[1], NULL); pthread_join(tid[0], NULL); if (count != iterations * 2) printf("Error: %d\n",count); else printf("Value as expected: count = %d\n", count); pthread_exit(NULL); } void *work_function(void *param) { long int max_iter = (long int) param; int i, tmp; pid_t pid = getpid(); pthread_t id = pthread_self(); i = pthread_mutex_lock(&mut); printf("%d\n", i); for(i = 0; i < max_iter; i++) { tmp = count; tmp ++; printf("in thread: pid=%d and id=%u count=%d new\n", (unsigned int) pid, (unsigned int) id, count); // sleep(1); count = tmp; printf("haha\n"); } pthread_mutex_unlock(&mut); pthread_exit(NULL); } 

Le résultat suivant est produit lorsque 3 est passé en tant qu’argument de ligne de commande.

 22 22 in thread: pid=36767 and id=6819840 count=0 new in thread: pid=36767 and id=7356416 count=0 new haha haha in thread: pid=36767 and id=6819840 count=1 new in thread: pid=36767 and id=7356416 count=1 new haha haha in thread: pid=36767 and id=6819840 count=2 new in thread: pid=36767 and id=7356416 count=2 new haha haha Error: 3 

L’initialisation de pthread_mutex_t mut résolu mon problème en plaçant le code suivant sous main méthode main .

 pthread_mutex_init(&mut, NULL);