在使用pthread_mutex_timedlock时,由于错误理解,导致并没有产生想要的效果。这里记录下:
先用pthread_mutex_lock进入锁,再用pthread_mutex_timedlock进入锁,结果发现第二次超时并没有其效果。
代码模拟如下:
1 #include <string.h> 2 #include <pthread.h> 3 #include <stdio.h> 4 #include <time.h> 5 uint64_t CTime::getCurrentMilliSecond() 6 { 7 struct timespec tp; 8 if (clock_gettime(CLOCK_MONOTONIC, &tp) == 0) 9 { 10 uint64_t ms = (uint64_t)1000 * tp.tv_sec + tp.tv_nsec / 1000000; 11 return ms; 12 } 13 return 0; 14 } 15 int main(void) 16 { 17 int err; 18 struct timespec tout; //纳秒级别 19 struct tm *tmp; 20 char buf[64]; 21 22 pthread_mutex_t lock; 23 pthread_mutex_init(&lock, NULL);//初始化锁 24 pthread_mutex_lock(&lock); //先进入锁 25 printf("mutex1 is locked.\n"); 26 27 tout.tv_sec += 5; //延迟5s才释放第二把锁 28 pthread_mutex_timedlock(&lock, &tout); 29 printf("mutex2 is locked.\n"); 30 31 return 0; 32 }
仔细查看书中对pthread_mutex_timedlock的解释:
int pthread_mutex_timedlock(pthread_mutex_t mutex, const struct timespec *tsptr);
当程序试图获取一个已加锁的互斥量时,pthread_mutex_timedlock互斥量原语允许绑定线程阻塞时间。pthread_mutex_timedlock函数与pthread_mutex_lock函数是基本等价的,但是在达到超时时间时,pthread_mutex_timedlock不会对互斥量进行加锁,而是返回错误码ETIMEOUT.
超时指定愿意等待的绝对时间(与相对时间对比而言,指定在时间X之前可以阻塞等待,而不是说愿意阻塞Y秒)。这个超时时间是用timespec结构来表示,它用秒和纳秒来描述时间。
发现是自己理解错误了,tsptr是绝对时间,不是相对时间。,所以后面代码修改如下,发现可以了:
1 #include <string.h> 2 #include <pthread.h> 3 #include <stdio.h> 4 #include <time.h> 5 uint64_t CTime::getCurrentMilliSecond() 6 { 7 struct timespec tp; 8 if (clock_gettime(CLOCK_MONOTONIC, &tp) == 0) 9 { 10 uint64_t ms = (uint64_t)1000 * tp.tv_sec + tp.tv_nsec / 1000000; 11 return ms; 12 } 13 return 0; 14 } 15 int main(void) 16 { 17 int err; 18 struct timespec tout; //纳秒级别 19 struct tm *tmp; 20 char buf[64]; 21 22 pthread_mutex_t lock; 23 pthread_mutex_init(&lock, NULL);//初始化锁 24 pthread_mutex_lock(&lock); //先进入锁 25 printf("mutex1 is locked.\n"); 26 27 clock_gettime(CLOCK_REALTIME, &tout);//获取当前时间 28 tout.tv_sec += 5; //延迟5s才释放第二把锁 29 pthread_mutex_timedlock(&lock, &tout); 30 printf("mutex2 is locked.\n"); 31 32 return 0; 33 }
原文:https://www.cnblogs.com/ho966/p/12249076.html