子进程打印提高部分

#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);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

viper困告了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值