筛质数的例子。任务窗口加大,做成数组,线程间通信 队列=管道,即实现 顺序存储的循环队列

mypipe.h[c] vim * -p

.h文件

  • 条件编译
  • 管道的大小 io的效率
#ifndef MYPIPE_H__
#define MYPIPE_H__
 
#define PIPESIZE 1024
#define MYPIPE_READ 0x00000001UL
#define MYPIPE_WEITE 0x00000002UL
typedef void mypipe_t;
 
mypipe_t* mypipe_init(*void);
 
//注册身份,是读/写者,使用位图
int mypipe_register(mypipe_t *,int opmap);
//注销身份
int mypipe_unregister(mypipe_t*,int opmap);
//读写管道
 
//返回读到多少字节数
int mypipe_read(mypipe_t *,void *buf,size_t size);
int mypipe_write(mypipe_t *,const void *buf,size_t  )
int mypipe_destroy(mypipe_t *);
 
#endif
  • 封装数据类型并隐藏
  • 当 当前管道空 且只有读者 没有写者 读者退出,作计数
#include<stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "mypipe.h"
 
 
struct mypipe_st{
	int head;
	int tail;
	char data[PIPESIZE];
	int datasize;//记录管道中有多少有效字节数
	int count_rd;
	int count_wr;
	//多线程并发
	pthread_mutex_t mut;//对当前管道的使用 独占 方式
	pthread_cond_t cond; //通知法
};
 
mypipe_t* mypipe_init()
{
	//申请内存空间
	struct mypipe_st *me;
	me=malloc(sizeof(*me));
	//malloc 失败,返回空指针
	if(me==NULL)
		return NULL;
	me->head=0;
	me->tail=0;
	me->datasize=0;
	me->count_rd=0;
	me->count_wr=0;
	pthread_mutex_init(&me->mut,NULL);
	pthread_cond_init(&me->cond,NULL);
	return me;
}
 
int mypipe_register(mypipe_t *,int opmap)
{
	/*if error*/
	
	pthread_mutex_lock(&me->mut);
	if(opmap&MYPIPE_READ)
		me->count_rd++;
	if(opmap&MYPIPE_WRITE)
		me->count_wr++;
	//管道至少要凑齐读写双方
	
	pthread_cond_broadcast(&me->cond);
	//如果读者/写者不存在
	while(me->count_rd<=0||me->count_wr<=0)
		pthread_cond_wait(&me->cond,&me->mut);
	
	pthread_mut_unlock(&me->mut);
	return 0;
}
 
int mypipe_unregister(mypipe_t*,int opmap)
{
	/*if error*/
	pthread_mutex_lock(&me->mut);
	if(opmap&MYPIPE_RD)
		me->count_rd--;
	if(opmap&MYPIPE_WR)
		me->count_wr--;
	pthrad_cond_broadcast(&me->cond);
	pthread_mutex_unlock(&me->mut);
}
 
//别人看不见
static int mypipe_readbyte_unlocked(struct mypipe_st*me,char *datap)
{
	if(me->datasize<=0)
		return -1;
	*datap;=me->data[me->head];
	me->head=next(me->head);
	me->datasize--;
	return 0;
}
 
int mypipe_read(mypipe_t *ptr,void *buf,size_t count)
{
	struct mypipe_st *me=ptr;
	pthread_mutex_lock(&me->mut);
	
	while(me->datasize<=0&&me->count_wr>0)
	{
		//解锁,在临界区等待
		pthread_cond_wait(&me->cond,&me->mut);
	}
	if(me->datasize<=0&&me->count_wr<=0)
	{
		pthread_mutex_unlock(&me->mut);
		return 0;
	}
	for(i=0;i<count;i++)
	{
		if(mypipe_readbyte_unlocked(me,buf+i) !=0)
			break;
	}
	pthread_cond_broadcast(&me->cond);//惊群
	pthread_mutex_unlock(&me->mut);
	
	return i ;//返回读到多少内容
}
int mypipe_write(mypipe_t *,const void *buf,size_t  )
{
	
}
int mypipe_destroy(mypipe_t *ptr)
{
	struct mypipe_st *me=ptr;
	pthread_mutex_destroy(&me->mut);
	pthread_mutex_destroy(&me->cond);
	
	free(ptr);
	return 0;
}
 

op的位置 权限信息。指针存进数组,返回下标 ;fd;中间层(二次封装时)判断权限