信号量 int
互斥锁 bool
用互斥锁来保护某一个资源,比如串口,某一个时刻只能有一个线程访问
如果man 3 pthread_mutex_init时提示找不到函数,说明你没有安装pthread的man手册。
安装方法:
1)虚拟机上网
2)sudo apt-get install manpages-posix-dev
上锁:马上用这个资源了,上厕所锁门
解锁:用完这个资源饿了,出厕所开门
互斥锁/互斥信号量代码
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <pthread.h>
char buf[200] = {0};
pthread_mutex_t mutex;
void *func(void *arg)
{
//sleep(1);
while(1)
{
pthread_mutex_lock(&mutex);
if(!strncmp(buf, "end", 3))//注意此函数可以比较个数 “n”
{
break;//return 0或者exit(0)加头文件 此处都是可以的
}
printf("本次输入了%d个字符。\n", strlen(buf));//注意此函数用法
memset(buf, 0, sizeof(buf));
//pthread_mutex_unlock(&mutex);
}
}
int main(void)
{
int ret = -1;
pthread_t th = -1;
pthread_mutex_init(&mutex, NULL);
ret = pthread_create(&th, NULL, func, NULL);
if(ret < 0)
{
printf("pthred error.\n");
exit(-1);
}
printf("输入一个字符串,以回车结束。\n");
while(1)
{
//pthread_mutex_lock(&mutex);
scanf("%s", buf);//注意此函数的用法
if(!strncmp(buf, "end", 3))//注意此函数可以比较个数 “n”
{
printf("程序结束。\n");
pthread_mutex_unlock(&mutex);
break;//return 0或者exit(0)加头文件 此处都是可以的
}
pthread_mutex_unlock(&mutex);
}
//回收子线程
printf("等待回收子线程.\n");
pthread_join(th, NULL);
if(ret < 0)
{
printf("pthred error.\n");
exit(-1);
}
printf("回收子线程成功.\n");
pthread_mutex_destroy(&mutex);
return 0;
}
解锁上锁只是为了保护这一段代码不会被打断,能执行完;