当程序试图获取一个已加锁的互斥量时,pthread_mutex_timedlock互斥量原语允许绑定线程阻塞时间。pthread_mutex_timedlock函数与pthread_mutex_lock函数是基本等价的,但是在达到超时时间时,pthread_mutex_timedlock不会对互斥量进行加锁,而是返回错误码ETIMEOUT.
#include <pthread.h>
#include <time.h>
int pthread_mutex_timedlock(pthread_mutex_t mutex, const struct timespec *tsptr);
返回值:若成功,返回0;否则,返回错误编号
超时指定愿意等待的绝对时间(与相对时间对比而言,指定在时间X之前可以阻塞等待,而不是说愿意阻塞Y秒)。这个超时时间是用timespec结构来表示,它用秒和纳秒来描述时间。
实例:
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <pthread.h>
int main(void)
{
int err;
struct timespec tout; //纳秒级别
struct tm *tmp;
char buf[64];
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; //初始化锁
//1
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); //strftime(char *str, size_t maxsize, const char *fmt, struct tm *time)
//按照参数fmt所设定格式将time类型的参数格式化为日期时间信息,然后存储在字符串str中(至多maxsize 个字符)
//参考http://ganquan.info/standard-c/function/strftime
printf("Current time is %s.\n", buf);
tout.tv_sec += 10; //延迟10s
//2
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));
}
return 0;
}
运行结果如下:
mutex is locked.
Current time is 09:28:00 PM.
The time is now 09:28:10 PM
Can't lock mutex again: Connection timed out
这个程序故意对它已有的互斥量进行加锁,目的是演示pthread_mutex_timedlock函数是如何工作的。不推荐在实际应用中使用这种策略,因为它会导致死锁