互斥锁超时函数pthread_mutex_timedlock函数实例

说明:代码来源于 《UNIX环境高级编程》第三版一书

apue.h  头文件来源该书的官方网站:http://csapp.cs.cmu.edu/

环境安装参考:http://blog.csdn.net/freestyle4568world/article/details/39269129

系统环境:centos6.9

代码在gcc编译器下正确编译:    gcc main.c -lapue -lpthread -lrt

如果是在eclipse运行需求对工程进行配置

右键工程->properties(属性)

按照下图配置加入三个共享库链接

代码完整实例:

#include "apue.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;

	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);
	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);

	/*this do something work */

	//pthread_mutex_unlock(&tout);

	if(err == 0 ){
		printf("mutex locked again!\n");
	}else{
		printf("can't locak mvtex again:%s\n",strerror(err));
	}
	exit(0);



}

 

运行结果:


mutex is locked
current time is 10:05:50 AM
the time is now 10:06:00 AM
can't locak mvtex again:Connection timed out

结论:

程序对线程互斥量进行加锁后并没有解锁

而是等待pthread_mutex_timedlock捕获到程序超时抛出错误。

 

添加评论

友情链接:蝴蝶教程