
操作系统实验系统调用.doc
3页实验六 系统调用学时:2学时1.实验内容:系统调用实验2.实验目的:通过调用PV操作解决生产者、消费者问题,了解系统中并发进程是怎样同步执行的3.实验题目:编写一段程序模拟PV操作实现进程同步,且用PV操作解决生产者、消费者问题4.实验提示:⑴PV操作由P操作原语和V操作原语组成P操作原语P(s)将信号量s减1,若s<0则执行原语的进程被置成等待状态V操作原语V(s)将信号量s加1,若s<=0则释放一个等待的进程⑵生产者、消费者问题主要解决的是进程并发执行时访问公共变量的问题假定有一个生产者和一个消费者生产者每次生产一个产品,并把产品存入共享缓冲区供消费者取走消费者每次从共享缓冲区取出一个产品去消费禁止生产者将产品放入已满的缓冲区,禁止消费者从空缓冲区内取产品⑶模拟程序中对应关系如下:产品数量int _nCurrProductor共享缓冲区大小int MaxBuffer信号量spthread_mutex_t _dealmutexP(s)原语pthread_mutex_lock(&_dealmutex)V(s)原语pthread_mutex_unlock(&_dealmutex)生产一个产品_nCurrProductor ++消费一个产品_nCurrProductor --实例代码://进程同步生产者、消费者实例pcustomer.c//运行环境Redhad9.0 gcc 4.0#include
\n",_nCurrProductor); } Else { _nCurrProductor ++; //生产一个产品 printf("当前的产品数[%6d] 生产了一个产品\n",_nCurrProductor); } pthread_mutex_unlock(&_dealmutex); //信号灯解锁 sleep(2); }}void* customer(void *arg) { //消费者进程 while(1) { pthread_mutex_lock(&_dealmutex); //信号灯锁定 if(_nCurrProductor > 0) { _nCurrProductor --; //消费一个产品 printf("当前的产品数[%6d] 消费了一个产品\n",_nCurrProductor); } else { printf("当前的产品数[%6d] 加快生产速度呀,没有产品了\n",_nCurrProductor); } pthread_mutex_unlock(&_dealmutex); //信号灯解锁 sleep(3); }}int main(int argc, char** argv) { printf("开始!\n"); pthread_mutex_init(&_dealmutex, NULL); //信号灯初始化 pthread_t pt1; pthread_t pt2; //建立生产者和消费者进程 int pret2 = pthread_create(&pt2, NULL, customer, NULL); int pret1 = pthread_create(&pt1, NULL, producer, NULL); if(pret1 != 0 || pret2 != 0) { printf("进程创建失败!\n"); exit(1); } while(1) { } pthread_join(pt1, NULL); pthread_join(pt2, NULL); printf("结束!\n"); return 0;}运行结果:[root@redlinux ys]# gcc -lpthread pcustomer.c -o pcustomer.o[root@redlinux ys]# ./pcustomer.o开始!当前的产品数[ 0] 加快生产速度呀,没有产品了。
当前的产品数[ 1] 生产了一个产品当前的产品数[ 2] 生产了一个产品当前的产品数[ 1] 消费了一个产品当前的产品数[ 2] 生产了一个产品当前的产品数[ 1] 消费了一个产品当前的产品数[ 2] 生产了一个产品当前的产品数[ 3] 生产了一个产品当前的产品数[ 2] 消费了一个产品当前的产品数[ 3] 生产了一个产品当前的产品数[ 2] 消费了一个产品当前的产品数[ 3] 生产了一个产品当前的产品数[ 4] 生产了一个产品当前的产品数[ 3] 消费了一个产品当前的产品数[ 4] 生产了一个产品。
