进程间通信之 信号量
定义:信号量是一个计数器,用于多进程对共享数据对象的存取访问控制。为了获得共享资源,进程需要执行下列操作
信号量使用步骤:
1:初始化信号量---->int sem_init(sem_t *sem, int pshared, unsigned int value);
2:申请资源,并对信号量做减一操作----->int sem_wait(sem_t *sem);
3:释放资源,并对信号量做加一操作------>int sem_post(sem_t *sem);
测试程序
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
int num = 0;
void *func1(void *sem)
{
int sval;
srand((unsigned)time(0));
while(1)
{
int r = rand() % 3;
sleep(r);
if(0 == sem_wait(sem))
{
num++;
printf("1 get it\n");
}
sleep(r);
printf("1 pass the ball\n");
sem_post(sem);
}
}
void *func2(void *sem)
{
int sval;
srand((unsigned)time(0));
while(1)
{
int r = rand() % 3;
sleep(r);
if(0 == sem_wait(sem))
{
num++;
printf("2 get it\n");
}
sleep(r);
printf("2 pass the ball\n");
sem_post(sem);
}
}
void *func3(void *sem)
{
int sval;
srand((unsigned)time(0));
while(1)
{
int r = rand() % 3;
sleep(r);
if(0 == sem_wait(sem))
{
num++;
printf("3 get it\n");
}
sleep(r);
printf("3 pass the ball\n");
sem_post(sem);
}
}
int main()
{
sem_t sem;
int pshared = 1;
pthread_t tid;
pthread_attr_t attr;
sem_init(&sem,pshared,1);
if(0 != pthread_attr_init(&attr))
perror("pthread_attr_init");
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); //设置分离属性
printf("start\n");
if(0 != pthread_create(&tid,&attr,func1,&sem))
perror("pthread_create");
if(0 != pthread_create(&tid,&attr,func2,&sem))
perror("pthread_create");
if(0 != pthread_create(&tid,&attr,func3,&sem))
perror("pthread_create");
while(1)
{
if(30 == num)
{
break;
printf("finshed\n");
}
}
return 0;
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。