C語言執行緒例項(生產者和消費者)
阿新 • • 發佈:2019-02-19
附上程式碼,作為以後的參考。
/***********main.c************/ #include "customer.h" #include "producer.h" #include "data.h" #include <pthread.h> #include <stdio.h> /******************************************************************* **實現生產者執行緒生產資料放入一個單向連結串列中,消費者執行緒負責消費資料***** *******************************************************************/ int main(){ pthread_t thread_pro; pthread_t thread_cons; printf("create....\n"); //建立生產者執行緒。 pthread_create(&thread_pro,NULL,(void *)producer,NULL); //建立消費者執行緒。 pthread_create(&thread_cons,NULL,(void *)customer,NULL); printf("finished!\n"); while(1){ } return 0; }
/************data.h***********/
#ifndef DATA_H_
#define DATA_H_
//單向連結串列資料結構
struct product{
struct product *pre_product;
char product_data[20];
struct product *next_product;
};
//向單向連結串列中加入一個節點(生產)。
void addProduct(char *product_data);
//從單向連結串列中取出全部節點資訊(消費)。
void consProduct();
#endif
/***********data.c************/ #include "data.h" #include <stdio.h> #include <stdlib.h> #include <string.h> struct product *present_product=NULL; struct product *pre_product = NULL; int lock=0; void addProduct(char *product_data){ while(lock==1); lock=1; struct product *new_product=malloc(sizeof(struct product)); if(present_product==NULL){ new_product->pre_product=NULL; strcpy( new_product->product_data,product_data); new_product->next_product=NULL; present_product=new_product; }else{ new_product->pre_product=present_product; strcpy( new_product->product_data,product_data); new_product->next_product=NULL; present_product->next_product=new_product; present_product=new_product; } lock=0; } void consProduct(){ while(lock==1); lock=1; while(present_product!=NULL){ pre_product=present_product->pre_product; printf("%s\n",present_product->product_data); if(pre_product!=NULL){ pre_product->next_product=0; } free(present_product); present_product=pre_product; } lock=0; }
/*************producer.h*************/
#ifndef PRODUCER_H_
#define PRODUCER_H_
//生產者執行生產任務
void producer();
#endif
/*************producer.c**************/ #include "producer.h" #include "data.h" #include <stdio.h> #include <string.h> #include <stdlib.h> int temp_i=0; void producer(){ char temp[20]={0}; while(1){ sprintf(temp,"number___%d",temp_i); addProduct(temp); temp_i++; usleep((int)(rand()/2000)); } }
/************customer.h***********/
#ifndef CUSTOMER_H_
#define CUSTOMER_H_
//消費者執行消費任務。
void customer();
#endif
/*************customer.c*************/
#include "customer.h"
#include "data.h"
#include <stdlib.h>
#include <stdio.h>
void customer(){
while(1){
consProduct();
printf("-------------\n");
usleep((int)(rand()/1000));
}
}
執行截圖:
(---------完---------)