单生产者 单消费者

本文介绍了一个简单的线程安全事件循环实现方案,通过使用结构体数组存储事件,并利用头尾指针进行读写操作,确保了并发环境下的正确性和安全性。
#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);

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值