pthread_mutex_timedlock


函數pthread_mutex_timedlock
當線程試圖獲取一個已加鎖的互斥變量時,pthread_mutex_timedlock互斥量原語允許綁定線程
阻塞的時間。pthread_mutex_timedlock函數與pthread_mutex_lock是基本等價的,但是在達到超時
時間值時,pthread_mutex_timedlock不會對互斥量進行加鎖,而是返回錯誤碼ETIMEDOUT。
#include<pthread.h>
#include<time.h>
int pthread_mutex_timedlock(pthread_mutex_t *restrict mutex,const struct timespec 

*restrict tsptr);
超時指定願意等待的絕對時間(與相對時間對比而言,指定在時間x之前可以阻塞等待,而不是說願

意阻塞Y秒)。這個超時時間是用timespec結構來表示的,它用秒和納秒來描述時間。

 

#include"apue.h"
#include <pthread.h>
#include<time.h>

int
main(void)
{
    int err;
    struct timespec tout;
    struct tm *tmp;
    char buf[64];
    pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

    pthread_mutex_lock(&lock);
    printf("mutex is locked\n");
    clock_gettime(CLOCK_REALTIME, &tout);
    tmp = localtime(&tout.tv_sec);
    strftime(buf, sizeof(buf), "%r", tmp);
    printf("current time is %s\n", buf);
    pthread_mutex_unlock(&lock);//這個是我自己加的,為了測試這個程序
    tout.tv_sec += 10;    /* 10 seconds from now */
    /* caution: this could lead to deadlock */
    err = pthread_mutex_timedlock(&lock, &tout);
    clock_gettime(CLOCK_REALTIME, &tout);
    tmp = localtime(&tout.tv_sec);
    strftime(buf, sizeof(buf), "%r", tmp);
    printf("the time is now %s\n", buf);
    if (err == 0)
        printf("mutex locked again!\n");
    else
        printf("can't lock mutex again: %s\n", strerror(err));
    exit(0);
}


免責聲明!

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



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