刚刚编辑了一大段,结果没了。那就简单说一次吧,我们要想使线程操作同步,就不能只是简简单单创建几个线程,需要引入新概念:信号量,类似于交通灯,信号量来决定线程是继续运行还是阻塞等待。
概念:信号量代表某一类资源,其值表示系统中该资源的数量。
操作:
信号量是一个受保护的变量,只能通过三种操作来访问
初始化------------------------------int sem_init(sem_t *sem, int pshared, unsigned int value);
P操作(申请资源)----------------int sem_wait(sem_t *sem); // P操作(信号量+1)
V操作(释放资源)----------------int sem_post(sem_t *sem); // V操作 (信号量-1)
/*
*线程1的func函数进行读操作,主线程进行写操作
*/
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <semaphore.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
void *pthread_func(void *arg);
char buf[32] = {0};
sem_t sem_r;
sem_t sem_w;
int main()
{
pthread_t a_thread;
if(sem_init(&sem_r,0,0) < 0) //init
{
perror("sem_init error");
return -1;
}
if(sem_init(&sem_w,0,1) < 0) //init
{
perror("sem_init error");
return -1;
}
if(pthread_create(&a_thread,NULL,pthread_func,NULL)!= 0) //thread 1
{
perror("pthread_create failed");
exit(-1);
}
else
{
do
{
sem_wait(&sem_w);//-1
printf("Input:\n");
fgets(buf,32,stdin);
sem_post(&sem_r);//+1
printf("Input %d characters successfully!\n",strlen(buf));
}while(strncmp(buf,"quit",4)!= 0);
}
return 0;
}
void *pthread_func(void *arg)
{
while(1)
{
sem_wait(&sem_r);
printf("Content:%s\n",buf);
sem_post(&sem_w);
}
}