- 论坛徽章:
- 0
|
有人帮我看下这个问题,为什么mutex 会被锁两次:
代码就是等待输入一个q返回,源代码如下,红色的两行结果
好奇怪,谢谢大牛了
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
static pthread_t thread;
static pthread_cond_t cond;
static pthread_mutex_t mutex;
static int flag = 1;
void * thr_fn(void * arg)
{
int ret =0 ;
struct timeval now;
struct timespec outtime;
printf("in function lock begin!\n");
ret = pthread_mutex_lock(&mutex);
printf("in function lock end! ret=%d\n",ret);
while (flag) {
printf("*****\n");
gettimeofday(&now, NULL);
outtime.tv_sec = now.tv_sec + 5;
outtime.tv_nsec = now.tv_usec * 1000;
pthread_cond_timedwait(&cond, &mutex, &outtime);
}
printf("in function unlock begin! ret=%d\n",ret);
ret=pthread_mutex_unlock(&mutex);
printf("in function unlock end! ret=%d\n",ret);
printf("cond thread exit\n");
}
int main(void)
{
int ret = 0;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
if (0 != pthread_create(&thread, NULL, thr_fn, NULL)) {
printf("error when create pthread,%d\n", errno);
return 1;
}
char c ;
while ((c = getchar()) != 'q');
printf("Now terminate the thread!\n");
printf("main lock begin!i ret=%d\n",ret);
ret= pthread_mutex_lock(&mutex);
printf("main lock end! ret=%d\n",ret);
flag = 0;
pthread_cond_signal(&cond);
printf("main unlock begin!\n");
ret = pthread_mutex_unlock(&mutex);
printf("main unlock end! ret=%d\n",ret);
printf("Wait for thread to exit\n");
pthread_join(thread, NULL);
printf("Bye\n");
return 0;
}
in function lock begin!
in function lock end! ret=0
*****
*****
q
Now terminate the thread!
main lock begin!i ret=0
main lock end! ret=0
main unlock begin!
main unlock end! ret=0
Wait for thread to exit
in function unlock begin! ret=0
in function unlock end! ret=0
cond thread exit
Bye |
|