生产者和消费者

/*
 * =====================================================================================
 *
 *       Filename:  producer_Consumer.c
 *
 *    Description:  使用单链表模拟缓冲区,生产者线程和消费者线程互斥访问缓冲区,利用互斥 
 *                  锁和条件变量来协调操作
 *
 *        Version:  1.0
 *        Created:  2014年10月22日 12时36分34秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Panhao (), 
 *   Organization:  
 *
 * =====================================================================================
 */

#include <stdio.h>
#include <SDL/SDL.h>
#include <SDL/SDL_thread.h>

SDL_mutex *mutex;
SDL_cond *cond;

typedef struct node{
	int val;
	struct node *next;
}Node;

Node *head = NULL;
//对生产产品计数,限制10个
int count = 1;


static int producerThread(void *ptr){
	while(count <= 10){
		if (SDL_LockMutex(mutex) == 0) {
			//全部消费完毕,head重新为空
			if(head == NULL){
				head = malloc(sizeof(struct node));
				head->next = NULL;
				head->val = count++;
				printf("生产者将数据 %d 放入缓冲区\n", head->val);
			}else{
				//head非空,新产品加入链表末尾
				struct node *p = head;
				while(p->next != NULL)
					p = p->next;
				p->next = malloc(sizeof(struct node));
				p = p->next;
				p->next = NULL;
				p->val = count++;
				printf("生产者将数据 %d 放入缓冲区\n", p->val);
			}
			
			SDL_CondSignal(cond);
	  		SDL_UnlockMutex(mutex);
			sleep(rand()%4);

		} else {
  			fprintf(stderr, "Couldn't lock mutex\n");
		}
		
	}

	return 0;
}

static int consumerThread(void *ptr){
	while(count <= 10 || head != NULL){
		if (SDL_LockMutex(mutex) == 0) {
			while(head == NULL){
			        SDL_CondWait(cond, mutex);
			}
			printf("\t消费者从缓冲区取数据 %d\n", head->val);
			Node *q = head;
			head = head->next;
			free(q);

  			SDL_UnlockMutex(mutex);
			sleep(rand()%4);

		} else {
  			fprintf(stderr, "Couldn't lock mutex\n");
		}
		
	}
	return 0;
}

int main(int argc, char *argv[])
{

	mutex = SDL_CreateMutex();
	if (!mutex) {
  		fprintf(stderr, "Couldn't create mutex\n");
  		return;
	}

	cond = SDL_CreateCond();
	if (!cond) {
  		fprintf(stderr, "Couldn't create cond\n");
  		return;
	}

    SDL_Thread *threadA;
    SDL_Thread *threadB;
    int         threadReturnValueA;
    int         threadReturnValueB;


    threadA = SDL_CreateThread(producerThread, (void *)NULL);
    if (NULL == threadA) {
        printf("\nSDL_CreateThread failed: %s\n", SDL_GetError());
    }
    
    threadB = SDL_CreateThread(consumerThread, (void *)NULL);
    if (NULL == threadB) {
        printf("\nSDL_CreateThread failed: %s\n", SDL_GetError());
    }
    
    SDL_WaitThread(threadA, &threadReturnValueA);
    SDL_WaitThread(threadB, &threadReturnValueB);

    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值