操作系统实验用的程序,保留一个。没什么技术含量,请见谅^_^

这个程序就是解决那个著名的“生产者—消费者”的问题,貌似线程的同步都讲这个问题,Java里面也有,不过操作起来貌似要更简单一点。

在这个程序里subp1()用来生产一个 int 数据,subp2()用来获取这个整数。首先是subp1()生产一个数据,subp2()再去获取这个数据。subp2()获取数据的首要条件是 subp1()已经生产了一个新的数据,subp1()生产一个新数据的前提是subp2()已经获得了subp1()生产的前一个数据。[#afdream.com#]

/*thread synchronization*/
/*thread.c*/
/*Afdream.com*/
/*2005-12-20*/
#include
#include
#include #include
#include #include

/*function of p opration*/
void P(int semid,int index)
{
struct sembuf sem;
sem.sem_num = index;
sem.sem_op = -1;
//mark of option:0 or IPC_NOWAIT and so on
sem.sem_flg = 0;
//the ‘1’ in this sentence means the number of commands
semop(semid,&sem,1);
return;
}

/*function of v opration*/
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 semid;
pthread_t p1,p2;
int sharedInt=0;
void *subp1();
void *subp2();

/*in Linux,the return of the function main must be int,cann’t be void*/
int main()
{
union semun semopts;
int res;
/*请求两个信号量*/
semid = semget(300,2,IPC_CREAT|0666);
if (semid<0) {
printf(“error”);
return;
}
/*初始化第一个信号量的值为1*/
semopts.val = 1;
res=semctl(semid,0,SETVAL,semopts);
/*初始化第二个信号量的值为0*/
semopts.val = 0;
res=semctl(semid,1,SETVAL,semopts);
if (res < 0) return;
/*创建两个线程*/
pthread_create(&p2,NULL,subp2,NULL);
pthread_create(&p1,NULL,subp1,NULL);
/*等待两个线程结束*/
pthread_join(p1,NULL);
pthread_join(p2,NULL);
semctl(semid,0,IPC_RMID,0);
}

/*produce number*/
void *subp1()
{
int i,j;
for (i=0; i<10;i++) {
sleep(i+1);
printf(“\nready to produce!\n”);
P(semid,0);
sharedInt++;
printf(“have produced %d!\n”,sharedInt);
V(semid,1);
}
return;
}

/*get number*/
void *subp2()
{
int i,j;
for (i=0;i<10;i++) {
sleep(10-i);
printf(“\nready to get!\n”);
P(semid,1);
printf(“have got %d!\n”,sharedInt);
V(semid,0);
}
return;
}

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.