linux线程笔记4

2017-01-05 20:15:16来源:CSDN作者:lu_k120人点击

互斥锁属性创建和销毁

     
 #include <pthread.h>       int pthread_mutexattr_init(pthread_mutexattr_t *attr);       int pthread_mutexattr_destroy(pthread_mutexattr *attr);

返回值:成功返回0 ,出错返回错误编号参数:attr:互斥锁属性

互斥锁进程共享属性操作

#include <pthread.h>int pthread_mutexattr_getpshared(const pthread_mutexattr_t *restrict attr,int *restrict pshared);int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr,int pshared);
返回值:成功返回0,出错返回错误编号参数:attr:互斥锁属性pshared:共享进程属性PTHREAD_PROCESS_PRIVATE(默认)//锁只能用于一个进程内部的两个线程进行互斥PTHREAD+PROCESS_SHARED//锁可以用于两个不同进程中的线程进行互斥

互斥锁类型操作

#include <pthread.h>int pthread_mutexattr_gettype(const pthread_mutexattr_t *restrict attr,int *restrict type);int pthread_mutexattr_settype(const pthread_mutexattr_t *attr,int type);
返回值:成功返回0 ,出错返回错误编号参数: attr:互斥锁属性type:互斥锁类型标准互斥锁:PTHREAD_MUTEX_NORMAL第一次上锁成功,第二次上锁会阻塞递归互斥锁:PTHREAD_MUTEX_RECURSIVE第一次上锁成功,第二次以上上锁还是成功,内部计数检错互斥锁:PTHREAD_MUTEX_ERRORCHECK第一次上锁成功,第二次上锁会出错默认互斥锁:PTHREAD_MUTEX_DEFAULT(同标准互斥锁)

例子:

#include <pthread.h>#include <stdio.h>#include <stdlib.h>#include <string.h>int main(int argc,char *argv[]){    	pthread_mutex_t  mutex;    	if(argc < 2){		printf("-usage:%s[error|mormal|recursival]/n",argv[0]);		exit(0);	}	pthread_mmutexattr_t mutexattr;   //定义互斥锁属性	pthread_mutexattr_init(&mutexattr);//初始化互斥锁属性	if(!strcmp(argv[1],"error")){		pthread_mutexattr_settype(&mutexattr,PTHREAD_MUTEX_ERRCHECK);	//设置互斥锁类型	}else if(!strcmp(argv[1],"normal")){		pthread_mutexattr_settype(&mutexattr,PTHREAD_MUTEX_NORMAL);	}else if(!strcmp(argv[1],"recursive")){		pthread_mutexattr_settype(&mutexattr,PTHREAD_MUTEX_RECURSIVE);	}	pthread_mutex_init(&mutex,&mutexattr);	//按照设置号的互斥锁类型创建初始化互斥锁	if(pthread_mutex_lock(&mutex) != 0){	//上锁		printf("lock failure/n");	}else{		printf("locak success/n");	}	if(pthread_mutex_lock(&mutex) != 0){	//上锁		printf("lock failure/n");	}else{		printf("locak success/n");	}	pthread_mutex_unlock(&mutex);		//解锁	pthread_mutex_unlock(&mutex);		//解锁	pthread_mutexattr_destroy(&mutexattr);	//销毁互斥锁属性	pthread_mutex_destroy(&mutex);		//销毁互斥锁	return 0;}编译:gcc -lpthread ***.c -o test运行:/.test normal	lock success	第一次上锁成功后,第二次上锁阻塞	ctrl+c	./test recursive	lock success		lock success	两次上锁都成功	./test error	lock success	lock failure	第一次上锁成功,第二次上锁会出错
   

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台