这个问题需要实现一个环形缓冲区,生产者向其中写入数据,消费者从中读取数据。我已经为数据类型做了这个。我想扩展它,以便它适用于任何原始数据类型,但还没有找到一个好的方法来做到这一点。我希望程序从命令行获取输入,例如“program_name data_type size_of_buffer”。
我可以模板化 buffer.start 指针并传递数据类型,但我不知道将数据类型名称分配给变量的方法。有人有想法么?
struct buffer{
int * start;
int size;
}buffer;
int * producer=NULL;
int * consumer=NULL;
bool donewriting;
bool sleeping;
void *mywrite(void *);
void *myread(void *);
void *mywrite(void * ){
do{
cout<<"In Thread 1"<<endl;
static int x=0;
*producer=x;
cout<<"Write thread: wrote value "<<x<<" into buffer"<<endl;
producer++;
if(producer==buffer.start+10)
{ producer=buffer.start;
donewriting=true;
}
if(x==5)
{
cout<<"Thread 1 going to sleep"<<endl;
Sleep(2000);
}
x++;
} while(producer!=buffer.start);
}
void *myread(void *){
while(!donewriting)
{ //cout<<"In Thread 2"<<endl;
if(consumer<producer)
{ cout<<"Read thread: read value "<<*consumer<<" from buffer"<<endl;
consumer++;
}
}
}
int main()
{
buffer.size=10;
buffer.start=new int(10);
producer=buffer.start;
consumer=buffer.start;
donewriting=false;
cout<<"In main"<<endl;
pthread_t writeThread,readThread;
pthread_create(&writeThread,NULL,mywrite,NULL);
pthread_create(&readThread,NULL,myread,NULL);
pthread_join(writeThread,NULL);
pthread_join(readThread,NULL);
return 0;
}