【发布时间】:2014-06-22 08:13:41
【问题描述】:
我正在编写具有以下结构的 C 多线程程序:
struct mystruct {
int a;
int b;
int c;
int d;
} Data;
void *thr_1();
void *thr_2();
int main(int argc, char *argv[]) {
pthread_t t_1,
t_2;
if (pthread_create(&t_1, NULL, thr_1, NULL)
|| pthread_create(&t_2, NULL, thr_2, NULL)) {
perror("pthread_create() on main()");
return -1;
}
while (a < 2000) {
/* do a lot of stuff with Data (never writes on it) */
}
pthread_cancel(thr_1);
pthread_cancel(thr_2);
pthread_join(thr_1, NULL);
pthread_join(thr_2, NULL);
return 0;
}
/* Threads */
void *thr_1() {
while (1) {
/* Read from stream and write to Data */
usleep(50000);
}
return NULL;
}
void *thr_2() {
while (1) {
/* do some stuff with Data (never writes on it) */
usleep(50000);
}
return NULL;
}
这段代码可以运行,但经过一些研究(竞争条件和线程安全)后,很明显这段代码可能会因为这些竞争条件而随时失败。我当时的第一个想法是使用互斥锁在写入时锁定结构的成员并在之后释放它,但是在主循环和 thr_2 中对 Data 结构的读取访问过多。到目前为止,我的解决方案是创建 2 个访问函数,一个读取数据,一个写入数据,在这些函数内部,使用互斥锁来锁定写入。这个丑陋的解决方案对我来说更像是一个黑客......所以,最后,我的问题是:有没有更好的方法来做到这一点?最好没有访问数据所需的任何功能。
非常感谢!
【问题讨论】:
-
你不喜欢互斥锁?
-
我很喜欢...但是读取的数据太多...并且对于每次读取我需要先锁定然后解锁...必须有更好的方法...。
标签: c multithreading thread-safety pthreads