递归锁在同一线程 内起作用。
- //线程属性
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- pthread_mutex_t g_mutex;
- void test_fun(void);
- static void thread_init(void)
- {
- //初始化锁的属性
- pthread_mutexattr_t attr;
- pthread_mutexattr_init(&attr);
- pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP);//设置锁的属性为可递归
- //设置锁的属性
- pthread_mutex_init(&g_mutex, &attr);
- //销毁
- pthread_mutexattr_destroy(&attr);
- }
- //线程执行函数
- void* thr_fun(void* arg)
- {
- int ret;
- ret=pthread_mutex_lock(&g_mutex);
- if( ret!=0 )
- {
- perror("thread pthread_mutex_lock");
- exit(1);
- }
- printf("this is a thread !/n");
- test_fun();
- ret=pthread_mutex_unlock(&g_mutex);
- if( ret!=0 )
- {
- perror("thread pthread_mutex_unlock");
- exit(1);
- }
- return NULL;
- }
- //测试函数
- void test_fun(void)
- {
- int ret;
- ret=pthread_mutex_lock(&g_mutex);
- if( ret!=0 )
- {
- perror("test pthread_mutex_lock");
- exit(1);
- }
- printf("this is a test!/n");
- ret=pthread_mutex_unlock(&g_mutex);
- if( ret!=0 )
- {
- perror("test pthread_mutex_unlock");
- exit(1);
- }
- }
- int main(int argc, char *argv[])
- {
- int ret;
- thread_init();
- pthread_t tid;
- ret=pthread_create(&tid, NULL, thr_fun, NULL);
- if( ret!=0 )
- {
- perror("thread create");
- exit(1);
- }
- pthread_join(tid, NULL);
- return 0;
- }
执行结果为:
this is a thread !
this is a test!