zoukankan      html  css  js  c++  java
  • 【操作系统原理】【实验4】生产者消费者进程

    一、实验目的

    通过生产者—消费者例子,熟悉、掌握互斥同步编程。

    二、实验内容

    模拟实现生产者—消费者例子,当生产者生产了某种产品后,消费者才可以消费该产品,缓冲区里没有个数限制,并且生产者和消费者是两个独立的线程,所以生产者可以一直生产产品,消费者可以消费生产者生产的任意产品。生产者和消费者线程既要同步也需要互斥。

    三、实验代码

    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>
    #include <string.h>
    #include <unistd.h>
    
    struct msg
    {
    	int num;
    	struct msg * next;
    };
    struct msg * head;
    
    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
    
    void * consumer(void * pVoid)
    {
    	struct msg * mp;
    	struct msg * mpp;
    	while (1)
    	{
    		pthread_mutex_lock(&mutex);
    		if (NULL == head)
    			pthread_cond_wait(&cond, &mutex);
    		mp = head;
    		if (mp -> next)
    		{
    			while (mp -> next)
    			{
    				mpp = mp;
    				mp = mp -> next;
    			}
    			printf("Consume %d\n", mp -> num);
    			free(mp);
    			mpp -> next = mp = NULL;
    		} else {
    			printf("Consume %d\n", mp -> num);
    			free(mp);
    			head = mp = NULL;
    		}
    		pthread_mutex_unlock(&mutex);
    		sleep(2);
    	}
    	return pVoid;
    }
    
    void * producer(void * pVoid)
    {
    	struct msg * mp;
    	while (1)
    	{
    		mp = (struct msg *)malloc(sizeof(struct msg));
    		mp -> num = rand()%1000 + 1;
    		printf("Produce %d\n", mp -> num);
    		pthread_mutex_lock(&mutex);
    		mp -> next = head;
    		head = mp;
    		pthread_mutex_unlock(&mutex);
    		pthread_cond_signal(&cond);
    		sleep(1);
    	}
    	return pVoid;
    }
    
    int main(void)
    {
    	pthread_t pid;
    	pthread_t cid;
    	head = NULL;
    	int err;
    	err = pthread_create(&pid, NULL, producer, "producer");
    	if (0 != err)
    	{
    		fprintf(stderr, "create thread1 faild:.....!%s\n", strerror(err));
    		return -1;
    	}
    	err = pthread_create(&cid, NULL, consumer, "consumer");
    	if (0 != err)
    	{
    		fprintf(stderr, "creat thread2 failed:......!%s\n", strerror(err));
    		return -1;
    	}
    	pthread_join(pid, NULL);
    	pthread_join(cid, NULL);
    	return 0;
    }
    
    有了计划记得推动,不要原地踏步。
  • 相关阅读:
    第六篇:python高级之网络编程
    第五篇:python高级之面向对象高级
    sublime插件开发教程
    Metatable In Lua 浅尝辄止
    cocos2dx-lua绑定之代码编辑器
    sublime入门文章
    Sublime Text快捷键
    lua中文教程【高级知识】
    lua基本语法
    Lua 不是 C++
  • 原文地址:https://www.cnblogs.com/amnotgcs/p/15542926.html
Copyright © 2011-2022 走看看