【发布时间】:2011-06-05 14:16:10
【问题描述】:
我有一些目前看起来像这样的代码(简化)
/* instance in global var *mystruct, count initialized to 0 */
typedef struct {
volatile unsigned int count;
} mystruct_t;
pthread_mutex_t mymutex; // is initialized
/* one thread, goal: block while mystruct->count == 0 */
void x(void *n) {
while(1) {
pthread_mutex_lock(&mymutex);
if(mystruct->count != 0) break;
pthread_mutex_unlock(&mymutex);
}
pthread_mutex_unlock(&mymutex);
printf("count no longer equals zero");
pthread_exit((void*) 0)
}
/* another thread */
void y(void *n) {
sleep(10);
pthread_mutex_lock(&mymutex);
mystruct->count = 10;
pthread_mutex_unlock(&mymutex);
}
这对我来说似乎效率低下且错误——但我不知道更好的方法。有没有更好的方法,如果有,是什么?
【问题讨论】:
-
建议在
break退出while循环后解锁互斥锁。 -
或者,如果你很懒惰,你可以使用强大的互斥锁并让
pthread_exit“解锁”它...
标签: c multithreading pthreads posix