/*
* =====================================================================================
*
* 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;
}
生产者和消费者
最新推荐文章于 2017-11-21 16:08:09 发布