單生產者 單消費者

#include <stdio.h>
#include <pthread.h>


struct event_loop_buf
{
	int head,tail;//@range 0~49 
	int eventnum[50];
};

volatile struct event_loop_buf evlop[6];

init_evlop()
{
	int i,j;

	for(i=0; i<6; i++){
		evlop[i].head = 0;
		evlop[i].tail = 0;

		for(j=0;j<50;j++){
			evlop[i].eventnum[j] = -1;
		}
	}

}

int get_a_event(int line)
{
	int ret = 0;
	//head is the first valid data 
	int head_next = evlop[line].head+1 > 49 ? 0 : evlop[line].head+1;

	if(evlop[line].head != evlop[line].tail){
		if(evlop[line].eventnum[evlop[line].head] != -1){
			ret = evlop[line].eventnum[evlop[line].head];
			evlop[line].eventnum[evlop[line].head] = -1;
		}else{
			ret = -1;
		}
		evlop[line].head = head_next;
	}else{
		if(evlop[line].eventnum[evlop[line].head] != -1){
			//read head;
			//clear head;	
			ret = evlop[line].eventnum[evlop[line].head];
			evlop[line].eventnum[evlop[line].head] = -1;
		}else{
			ret = -1;
		}
	}

	return ret;
}

int insert_a_event(int line,int in)
{
	//tail is last valid data 
	int tail_next = evlop[line].tail+1 > 49 ? 0 : evlop[line].tail+1;

	if(tail_next != evlop[line].head){		
		evlop[line].eventnum[tail_next] = in;
		evlop[line].tail = tail_next;
	}else{
		return -1;
	}
	return 1;
}

void getev()
{
	int ret,count=0;
	while(1){
		while(-1 == (ret = get_a_event(1)));
		printf("                   get %d ret is %d\n",++count,ret);
		//sleep(1);
	}
}

int main()
{
	int n,count=0,ret;
	pthread_create(&n,NULL,getev,NULL);

	init_evlop();
        int i = 400;
	while(i-- > 0){
		while(-1 == (ret = insert_a_event(1,22+count)));
		printf(" %d insertret %d is %d\n",++count,22+count,ret);
		//sleep(3);

	}

    while(1)sleep(5);

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章