Ⅰ 用c语言编程实现用信号量实现读者--写者问题(要源代码)
汗 竟然是校友...
by monkeyking
Ⅱ 用c语言或c++编写编程实现生产者消费者或读写者的同步问题
实现一个队列CQueue
CQueue提供两个公有成员函数
addTail():往队列尾部增加一个元素
removeHead():读出并移除队列的第一个元素
生产者:两个线程通过调用CQueue::addTail()往队列中增加元素
消费者:一个线程通过调用CQueue::removeHead()从队列中读取元素
#include <iostream>
#include <list>
#include <windows.h>
#include <process.h>
using namespace std;
#define P(sem) WaitForSingleObject(sem,INFINITE)
#define V(sem) ReleaseSemaphore(sem,1,NULL)
class CQueue
{
public:
void addTail();//往队列尾部增加一个元素
void removeHead();//读出并移除队列的第一个元素
private:
list<int> L;
};
CQueue buffer;//全局的缓冲区
const int buf_size = 10;//缓冲区大小
static int GOODS_ID = 0;//商品序号
const int procers = 3;//生产者数量
const int consumers = 8;//消费者数量
void ProcerThread(void* param);
void ConsumerThread(void* param);
HANDLE empty,occupy,op_mutex;
int main()
{
int i;
int p_id[procers],c_id[consumers];
occupy = CreateSemaphore(NULL,0,buf_size,NULL);//占用位置
empty = CreateSemaphore(NULL,buf_size,buf_size,NULL);//空余位置
op_mutex = CreateSemaphore(NULL,1,1,NULL);//操作互斥量
for(i=0;i<procers;++i)
{
p_id[i] = i+1;
_beginthread(ProcerThread,0,p_id+i);
}
for(i=0;i<consumers;++i)
{
c_id[i] = i+1;
_beginthread(ConsumerThread,0,c_id+i);
}
while(getchar()=='\n') break;
return 0;
}
void CQueue::addTail()
{
L.insert(L.end(),++GOODS_ID);
}
void CQueue::removeHead()
{
cout<<*L.begin()<<endl;
L.erase(L.begin());
}
void ProcerThread(void* param)
{
int id = *(int*)param;
while(1)
{
P(empty);
P(op_mutex);
Sleep(100);
buffer.addTail();
printf("Procer_%d proced %d\n",id,GOODS_ID);
V(op_mutex);
V(occupy);
}
}
void ConsumerThread(void* param)
{
int id = *(int*)param;
while(1)
{
P(occupy);
P(op_mutex);
Sleep(100);
printf("Consumer_%d consumed ",id);
buffer.removeHead();
V(op_mutex);
V(empty);
}
}