1
为什么这个代码是坏有人可以给我解释一下:互斥理解
int data;
void* worker(void* arg __attribute__((unused))) {
pthread_mutex_t m;
pthread_mutex_init(&m, NULL);
for (int i = 0; i < N; i++) {
pthread_mutex_lock(&m);
data++;
pthread_mutex_unlock(&m);
}
pthread_mutex_destroy(&m);
return NULL;
}
这是确定的:
int data;
pthread_mutex_t m;
void* worker(void* arg __attribute__((unused))) {
for (int i = 0; i < N; i++) {
pthread_mutex_lock(&m);
data++;
pthread_mutex_unlock(&m);
}
return NULL;
}
// ...
pthread_mutex_init(&m, NULL);
// ...
pthread_mutex_destroy(&m);
// ..
我总是需要在全球范围内声明的变量互斥?
错误代码的实际含义是什么? –
它在某些输入上无法正常工作。 – Welez
http://stackoverflow.com/a/12776593/4593781,这篇文章可以帮助 –