【发布时间】:2017-05-08 01:45:58
【问题描述】:
使用Pthreads,假设线程1和2之间有一个全局共享变量foo。不使用互斥体从线程1读取foo的值是否线程安全?请注意,虽然线程 1 读取 foo,但线程 2 可能会更改其值并非不可能(但它当然会事先锁定互斥锁)。
情况是这样的:
#include <pthread.h>
...
int foo;
pthread_mutex_t mutex;
...
void *thread1(void *t) {
while (foo<10) {
// do stuff
}
pthread_exit(NULL);
}
void *thread1(void *t) {
...
pthread_mutex_lock(&mutex);
...
foo++;
...
pthread_mutex_unlock(&mutex);
...
pthread_exit(NULL);
}
int main() {
...
}
【问题讨论】:
-
我认为你需要锁定读写。否则,可能会出现“脏读”。
-
您的示例不清楚,因为您显示了两个函数
thread1()。大概,您打算使用thread1()和thread2(),或类似的东西。不能保证写入通常是原子的,因此您需要使用互斥锁来保护对foo的访问,以便读取和写入。如果foo是结构类型,那将是一个更严重的问题。但唯一安全(理智)的策略是在读取或写入共享变量之前锁定互斥锁。
标签: c multithreading thread-safety pthreads