#include <pthread.h>
#include <sys/types.h>
#include <sys/sem.h>
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int semID; //semID
/*P操作*/
void P(int semid,int index)
{
struct sembuf sem;
sem.sem_num = index;
sem.sem_op = -1;
sem.sem_flg = 0;
semop(semid,&sem,1);
return;
}
/*V操作*/
void V(int semid,int index)
{
struct sembuf sem;
sem.sem_num = index;
sem.sem_op = 1;
sem.sem_flg = 0;
semop(semid,&sem,1);
return;
}
int a=0;
/*线程1,负责计算*/
/*
void subp1()
{//负责将1加到100
int i =1;
for(;i<=100;i++)
{
P(semID,0);
printf("Thread 1 is adding!\n");
a += i;
V(semID,1);
}
return;
}
void subp2()
{
int i;
for( i=1;i<=100;i++){
//打印出内容
P(semID,1);
printf("Thread 2 is printing:");
printf("%d\n",a);
V(semID,0);
}
return 0;
}
*/
struct sharedItem
{
int sumNum;
};
int main()
{
key_t key =1;
/*创建信号灯:2个*/
semID = semget(key,2,IPC_CREAT | 0666);
//信号灯赋初值1
semctl(semID,0,SETVAL,1);
semctl(semID,1,SETVAL,0);
/*创建两个子进程*/
int pid1,pid2;
key_t sKey = 0x2233;
int shID;
shID = shmget(sKey,sizeof(struct sharedItem), IPC_CREAT|0666);
if((pid1 = fork()) == 0)
{
/*创建共享内存*/
struct sharedItem *sum = (struct sharedItem*)shmat(shID,NULL,0);
sum->sumNum = 0;
int i=1;
for(;i<=100;i++)
{
P(semID,0);
printf("Process 1 is adding now\n");
sum->sumNum += i;
V(semID,1);
}
shmdt(sum);
}else if((pid2 = fork())==0)
{
struct sharedItem *sum = (struct sharedItem*)shmat(shID,NULL,0);
int i =1;
for(;i<=100;i++)
{
P(semID,1);
printf("Process 2 is printing: %d\n",sum->sumNum); //打印
V(semID,0);
}
shmdt(sum);
}
//创建两个线程p1和P2
/*
pthread_t p1,p2;
int get1,get2;
get1 = pthread_create(&p1,NULL,(void*)subp1,NULL);
get2 = pthread_create(&p2,NULL,(void*)subp2,NULL);
//等待两个线程运行结束
pthread_join(p1,NULL);
pthread_join(p2,NULL);
*/
waitpid(pid1,NULL,0);
waitpid(pid2,NULL,0);
//删除信号灯
shmctl(shID,IPC_RMID,NULL);
int isDelete;
isDelete = semctl(semID,1,IPC_RMID,0);
}
利用子进程实验打印
最新推荐文章于 2024-01-23 23:45:38 发布