类型互斥量属性控制着互斥量的特性。POSIX定义了四种类型。
enum
{
PTHREAD_MUTEX_TIMED_NP,
PTHREAD_MUTEX_RECURSIVE_NP,
PTHREAD_MUTEX_ERRORCHECK_NP,
PTHREAD_MUTEX_ADAPTIVE_NP
};
其中,PTHREAD_MUTEX_TIMED_NP类型是标准(默认)的互斥量类型,并不作任何特殊的错误检查或死锁检查。PTHREAD_MUTEX_RECURSIVE_NP互斥量类型允许同一线程在互斥量解锁之前对该互斥量进行多次加锁。同一个递归互斥量维护锁的计数,在解锁的次数和加锁次数不同的情况下不会释放锁。即对同一互斥量加几次锁就要解几次锁。
涉及的函数
1.互斥量属性的初始化与回收
#include
int pthread_mutexattr_destroy(pthread_mutexattr_t *attr);
int pthread_mutexattr_init(pthread_mutexattr_t *attr);
返回值:若成功返回0,否则返回错误编号。
2.获取/设置互斥量属性
#include
int pthread_mutexattr_gettype(const pthread_mutexattr_t *restrict attr,
int *restrict type);
int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type);
返回值:若成功返回0,否则返回错误编号。
测试程序:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
pthread_mutex_t lock;
int g_val0, g_val1;
int func(void)
{
int ret, val;
ret = pthread_mutex_lock(&lock);
if (ret)
printf("func:lock:%s\n", strerror(ret));
val = g_val1+8;
#if 1
ret = pthread_mutex_unlock(&lock);
if (ret)
printf("func:unlock%s\n", strerror(ret));
#endif
return val;
}
void * test0(void * arg)
{
int ret;
ret = pthread_mutex_lock(&lock);
if (ret)
printf("lock:%s\n", strerror(ret));
sleep(5);
g_val0 = func();
printf("res=%d\n", g_val0);
ret = pthread_mutex_unlock(&lock);
if (ret)
printf("unlock%s\n", strerror(ret));
return NULL;
}
void * test1(void * arg)
{
sleep(1);
#if 1
int ret = pthread_mutex_lock(&lock);
if (ret)
printf("1:%s\n", strerror(ret));
printf("g_val0=%d\n", g_val0);
ret = pthread_mutex_unlock(&lock);
if (ret)
printf("1:unlock%s\n", strerror(ret));
#endif
return NULL;
}
int main(void)
{
int ret;
pthread_t tid[2];
pthread_attr_t attr;
pthread_mutexattr_t mutexattr;
pthread_attr_init(&attr);
pthread_mutexattr_init(&mutexattr);
pthread_attr_setdetachstate(&attr,
PTHREAD_CREATE_DETACHED);
pthread_mutexattr_settype(&mutexattr,
PTHREAD_MUTEX_RECURSIVE_NP);
pthread_mutex_init(&lock, &mutexattr);
pthread_mutexattr_destroy(&mutexattr);
ret = pthread_create(&tid[0], &attr,
test0, NULL);
if (ret) {
fprintf(stderr, "create:%s\n", strerror(ret));
exit(1);
}
ret = pthread_create(&tid[0], &attr,
test1, NULL);
if (ret) {
fprintf(stderr, "create:%s\n", strerror(ret));
exit(1);
}
pthread_attr_destroy(&attr);
pthread_exit(NULL);
}
|
阅读(851) | 评论(0) | 转发(0) |