互斥锁限制共享资源的访问
通过加锁,解锁操作实现限制共享资源的访问:
参考案例:
让线程t1使用的共享资源g_data数字等于3时,退出线程t1.
参考代码:
#include <stdio.h>
#include <pthread.h>
int g_data=0;//共享资源
pthread_mutex_t mutex;//创建锁(互斥量)
void *func1(void*arg)//参数3:调用无类型指针API
{
printf("t1:%ld thread is create\n",(unsigned long)pthread_self());
//pthread_self():返回自身线程id,为pthread_t类型
printf("t1:param is %d:\n",*((int*)arg));//转化为int*,再取值
pthread_mutex_lock(&mutex);//加锁
while(1)
{
printf("t1:%d\n",g_data++);
sleep(1);
if(g_data==3)
{
pthread_mutex_unlock(&mutex);//解锁
printf("t1:quit------------------------\n");
pthread_exit(NULL);
//exit(0);//进程结束崩了,线程一定退出
}
}
}
void *func2(void*arg)//参数3:调用无类型指针API
{
printf("t2:%ld thread is create\n",(unsigned long)pthread_self());
//pthread_self():返回自身线程id,为pthread_t类型
printf("t2:param is %d:\n",*((int*)arg));//转化为int*,再取值
while(1)
{
printf("t2:%d\n",g_data);
pthread_mutex_lock(&mutex);//加锁,别的线程上不了,阻塞线程(t1未解锁情况)
g_data++;
pthread_mutex_unlock(&mutex);//解锁,别的线程可以上了
sleep(1);
}
}
int main()
{
int ret;//返回值
pthread_t t1;
pthread_t t2;
pthread_mutex_init(&mutex,NULL);//参数2:锁的属性
int param=100;//参数4:调用时:将int*转化为void*.100:随便给的数
ret=pthread_create(&t1,NULL,func1,(void*)¶m);
//参数1:指针指向t1,NULL:线程属性,参数3:启动线程调用的函数,参数4:打印的值
ret=pthread_create(&t2,NULL,func2,(void*)¶m);
if(ret==0)
{
printf("main函数创建线程t1成功\n");
}
if(ret==0)
{
printf("main函数创建线程t2成功\n");
}
printf("main:%ld\n",(unsigned long)pthread_self());
while(1)
{
printf("main:%d\n",g_data);
sleep(1);
}
pthread_join(t1,NULL);//等待线程
pthread_join(t2,NULL);//等待线程
pthread_mutex_destroy(&mutex);//销毁这把锁
return 0;
}
说明:
1.当t1线程先执行时已加锁,t2线程为阻塞线程,无法上锁,当t1线程等于3退出解锁时,t2线程可以上锁并解锁。
2.当t2线程先执行时,加锁立马解锁,如果执行到t1线程,则还是一直到等于3.
3.main线程在整个过程中表现得随意,都能穿插,随缘即可。
4.exit(0);如果整个进程结束了,那么线程将全部结束
运行结果:
dazai@dazai:~$ gcc demo3.c -lpthread
dazai@dazai:~$ ./a.out
main函数创建线程t1成功
main函数创建线程t2成功
main:-1210710272
main:0
t2:-1219105984 thread is create
t2:param is 100:
t2:0
t1:-1210713280 thread is create
t1:param is 100:
t1:1
main:2
t2:3
t1:2
main:3
t1:quit------------------------
t2:4
main:5
t2:5
main:5
main:6
t2:6
main:7
t2:7