当前位置: 技术问答>linux和unix
mutex的疑问
来源: 互联网 发布时间:2016-11-02
本文导语: 代码如下,输出在最后,我看了一下输出觉得有点不对劲,为什么两个线程都能同时拥有mymutex? #include #include #include #include #include pthread_cond_t mycond; pthread_mutex_t mymutex; ...
代码如下,输出在最后,我看了一下输出觉得有点不对劲,为什么两个线程都能同时拥有mymutex?
输出如下:
Now the time is 17:59:44 in thread 258.
Now the time is 17:59:44 in thread 515.
Timeout in thread 515.
Now the time is 17:59:49 in thread 515.
Timeout in thread 258.
Now the time is 17:59:49 in thread 258.
#include
#include
#include
#include
#include
pthread_cond_t mycond;
pthread_mutex_t mymutex;
void *myfun1(void *)
{
timespec mytime;
mytime.tv_sec = time(NULL)+5;
mytime.tv_nsec = 0;
struct tm* stNowTime;
time_t tNowTime;
int ret;
pthread_mutex_lock(&mymutex);
time(&tNowTime);
stNowTime = localtime(&tNowTime);
printf("Now the time is %02d:%02d:%02d in thread %d.n",stNowTime->tm_hour,stNowTime->tm_min,stNowTime->tm_sec,pthread_self());
ret = pthread_cond_timedwait(&mycond, &mymutex,(const struct timespec *)&mytime);
if( ETIMEDOUT == ret )
{
printf( "Timeout in thread %d.n",pthread_self());
time(&tNowTime);
stNowTime = localtime(&tNowTime);
printf("Now the time is %02d:%02d:%02d in thread %d.n",stNowTime->tm_hour,stNowTime->tm_min,stNowTime->tm_sec,pthread_self());
pthread_mutex_unlock(&mymutex);
}
return 0;
}
void *myfun2(void *)
{
timespec mytime;
mytime.tv_sec = time(NULL)+5;
mytime.tv_nsec = 0;
struct tm* stNowTime;
time_t tNowTime;
int ret;
pthread_mutex_lock(&mymutex);
time(&tNowTime);
stNowTime = localtime(&tNowTime);
printf("Now the time is %02d:%02d:%02d in thread %d.n",stNowTime->tm_hour,stNowTime->tm_min,stNowTime->tm_sec,pthread_self());
ret = pthread_cond_timedwait(&mycond, &mymutex,(const struct timespec *)&mytime);
if( ETIMEDOUT == ret )
{
printf( "Timeout in thread %d.n",pthread_self());
time(&tNowTime);
stNowTime = localtime(&tNowTime);
printf("Now the time is %02d:%02d:%02d in thread %d.n",stNowTime->tm_hour,stNowTime->tm_min,stNowTime->tm_sec,pthread_self());
pthread_mutex_unlock(&mymutex);
}
return 0;
}
int main()
{
pthread_t mythread1,mythread2;
pthread_cond_init(&mycond,NULL);
pthread_mutex_init(&mymutex,NULL);
pthread_create(&mythread1,NULL,myfun1,NULL);
pthread_create(&mythread2,NULL,myfun2,NULL);
pthread_join(mythread1,NULL);
pthread_join(mythread2,NULL);
return 0;
}
输出如下:
Now the time is 17:59:44 in thread 258.
Now the time is 17:59:44 in thread 515.
Timeout in thread 515.
Now the time is 17:59:49 in thread 515.
Timeout in thread 258.
Now the time is 17:59:49 in thread 258.
|
pthread_cond_timedwait() 执行时,会首先对mutex解锁,返回后对mutex再次加锁。
并不是两个线程同时拥有mutex
另外,lz你两个函数的逻辑都一样,不用定义两个函数
可以简化
pthread_create(&mythread1,NULL,myfun1,NULL);
pthread_create(&mythread2,NULL,myfun1,NULL);
让两个线程执行同一个函数就行了
并不是两个线程同时拥有mutex
另外,lz你两个函数的逻辑都一样,不用定义两个函数
可以简化
pthread_create(&mythread1,NULL,myfun1,NULL);
pthread_create(&mythread2,NULL,myfun1,NULL);
让两个线程执行同一个函数就行了
|
这个才是正解
pthread_cond_timewait()会首先内部解锁一次。。
你这个pthread_cond_timewait()用错了。。