我试图理解为什么 pthread_mutex_init 需要在 pthread_mutex_lock 之后调用。
我编写了一个小程序,显示在 pthread_mutex_init 之前调用 pthread_mutex_lock 时行为很奇怪(见下文),但我不明白为什么会这样。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t mutex;
int count = 0;
void* do_stuff(int* param) {
int* count = (int*) param;
pthread_mutex_lock(&mutex);
(*count)++;
printf("Count was just incremented to: %d\n", *count);
pthread_mutex_unlock(&mutex);
return NULL;
}
int main(void) {
//pthread_mutex_init(&mutex, NULL); **TRYING TO FIGURE OUT WHY THIS IS NEEDED**
int * x;
*x = 10;
pthread_t *p_tids = malloc(sizeof(pthread_t)*5);
for (int i = 0; i < 5; i++) {
printf("this is i %d\n", i);
pthread_create( p_tids + i, NULL, (void*)do_stuff, (void*)&count );
}
for (int j =0; j < 5; j++) {
pthread_join( p_tids[j], NULL );
}
pthread_mutex_destroy(&mutex);
return 0;
}
在 main 开头调用 pthread_mutex_init 时,这就是预期的输出。
Count was just incremented to: 1
Count was just incremented to: 2
Count was just incremented to: 3
Count was just incremented to: 4
Count was just incremented to: 5
当 pthread_mutex_init 被注释掉时,每次程序运行时输出都会改变。
Ex 1:
Count was just incremented to: 1
Count was just incremented to: 5
Count was just incremented to: 2
Count was just incremented to: 3
Count was just incremented to: 4
Ex 2:
Count was just incremented to: 2
Count was just incremented to: 1
Count was just incremented to: 3
Count was just incremented to: 4
Count was just incremented to: 5
Ex 3:
Count was just incremented to: 1
Count was just incremented to: 2
Count was just incremented to: 1
Count was just incremented to: 3
Count was just incremented to: 4
为什么会这样?