前段时间在ubuntu下成功搭建了eclipse开发c语言的环境,今天学习了多线程以及同步异步实现,再加上前段时间看java实现的生产者消费者问题,于是产生了用C语言实现这个问题的想法。
主要用到的知识包括线程的创建,互斥量的使用,条件变量以及thread_join
用到了一个数组表示的栈,由于主要练的是多线程函数的使用,其它的一些个细节便没有仔细追究。源代码如下:
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
const int volumn = 6;
class Bread{
public:
int id;
Bread(){}
Bread(int i){id=i;}
};
class Basket{
private:
Bread *br;
int n; //num of the bread
pthread_mutex_t work_mutex;
pthread_cond_t work_con;
public:
Basket();
void Push(Bread& b);
void Pop(Bread& b);
};
Basket::Basket(){
br=new Bread[volumn];
n=0;
int res = pthread_mutex_init(&work_mutex,NULL);
if(res!=0){
perror("mutex init error");
return;
}
res = pthread_cond_init(&work_con,NULL);
if(res!=0){
perror("condition init error");
return;
}
}
void Basket::Push(Bread &b){
pthread_mutex_lock(&work_mutex);
if(n == volumn){
//is full
pthread_cond_wait(&work_con,&work_mutex);
}
br[n]=b;
n++;
pthread_mutex_unlock(&work_mutex);
pthread_cond_signal(&work_con);
}
void Basket::Pop(Bread &b){
pthread_mutex_lock(&work_mutex);
if(n==0){
//is empty
pthread_cond_wait(&work_con,&work_mutex);
}
b=br[n-1];
n--;
pthread_mutex_unlock(&work_mutex);
pthread_cond_signal(&work_con);
}
void *pthread_function(void*);
Basket *ba;
int main(){
int res;
ba = new Basket();
pthread_t a_thread;
res = pthread_create(&a_thread,NULL,pthread_function,NULL);
if(res!=0){
perror("thread create error");
exit(-1);
}
//main thread is producter.
for(int i=0;i<10;i++){
Bread brtmp(i);
ba->Push(brtmp);
printf("product bread number %d\n",brtmp.id);
sleep(0.5);
}
pthread_join(a_thread,NULL);
return 0;
}
void *pthread_function(void*){
Bread br;
for(int i=0;i<10;i++){
ba->Pop(br);
printf("consume bread number %d\n",br.id);
sleep(1);
}
pthread_exit(0);
}
刚开始的时候没有加上pthread_join这个函数,导致主线程老早结束之后还有一个线程便也自动结束,加上之后便不会有这个问题。
调试的时候eclipse是可以选择执行代码的,还没有发现同时调试两个线程的方法,以后再看吧。
apue确实讲的不错,争取好好学。