互斥锁的理解
Mutex understanding
有人可以向我解释为什么这段代码不好吗:
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);
// ..
我是否总是需要全局声明互斥变量?
本地 mutex
的问题在于它只是 mutex
的本地可访问版本...因此当 thread
锁定 mutex
以便共享一些全局可访问的数据,数据本身不受保护,因为每个其他 thread
都会有自己的本地 mutex
可以锁定和解锁。它破坏了互斥的全部意义。
我建议也考虑异常安全。在此特定示例中,您只是在 mutex
lock/unlock
中间执行 data++
。那么,如果您将来在 pthread_mutex_unlock(&m);
之前放置另一个可能引发异常的语句怎么办。了解 RAII.
有人可以向我解释为什么这段代码不好吗:
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);
// ..
我是否总是需要全局声明互斥变量?
本地 mutex
的问题在于它只是 mutex
的本地可访问版本...因此当 thread
锁定 mutex
以便共享一些全局可访问的数据,数据本身不受保护,因为每个其他 thread
都会有自己的本地 mutex
可以锁定和解锁。它破坏了互斥的全部意义。
我建议也考虑异常安全。在此特定示例中,您只是在 mutex
lock/unlock
中间执行 data++
。那么,如果您将来在 pthread_mutex_unlock(&m);
之前放置另一个可能引发异常的语句怎么办。了解 RAII.