pthread_mutex_timedlock使用的誤解


在使用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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM