e { union semun arg; //seting value for mutex semaphore arg.val=1; if(semctl(semid,0,SETVAL,arg)==-1) { perror("setting semaphore value failed "); return -1; } //set value for synchronous semaphore arg.val=num; //the num means that the producer can continue to produce num products if(semctl(semid,1,SETVAL,arg)==-1) { perror("setting semaphore value failed "); return -1; } //the last semaphores value is default //the default value 0 means that the consumer is not use any product now }
基本上这样,就算完成了生产者和消费者的前期工作。我们可以看到,在核心代码中,我们只需要“装模作样”的将代码“各就各位”即可,当然这需要你理解生产者消费者这个基本模型。而在下面的准备代码中,则需要我们理解关于信号量和共享内存的一些基本函数。 最后再说说使用,建议先运行一个生产者和一个消费者,观察两者是如何协调工作的。然后再只运行一个生产者或一个消费者,看其是否会阻塞。了解了以上情况后,你就可以同时运行多个生产者和消费者了
|