操作系统生产者与消费者问题实验报告 联系客服

发布时间 : 星期日 文章操作系统生产者与消费者问题实验报告更新完毕开始阅读fd4161c6bf1e650e52ea551810a6f524ccbfcb9b

.

char Temp_entity=Thread_Info[j].entity; double Temp_delay=Thread_Info[j].delay;

printf(\ int Temp_request=Thread_Info[j].n_request; for(int k=0;k

printf(\ cout<

printf(\

empty_semaphore=CreateSemaphore (NULL,n_Buffer_or_Critical,n_Buffer_or_Critical, \

h_mutex=CreateMutex(NULL,FALSE,\

for(j=0;j<(int)n_Thread;j++){

std::string lp=\ int temp=j; while(temp){

char c=(char)(temp); lp+=c; temp/=10; }

h_Semaphore[j+1]=CreateSemaphore(NULL,0,n_Thread,lp.c_str()); }

for(i=0;i<(int)n_Thread;i++){ if(Thread_Info[i].entity=='P')

h_Thread[i]=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)(Produce), &(Thread_Info[i]),0,NULL);

else

h_Thread[i]=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)(Consume), &(Thread_Info[i]),0,NULL);

}

wait_for_all=WaitForMultipleObjects(n_Thread,h_Thread,TRUE,-1); printf(\_getch(); return 0; }

bool IfInOtherRequest(int req)

.

.

{

for(int i=0;i

for(int j=0;j

int FindProducePosition() {

int EmptyPosition;

for(int i=0;i

return EmptyPosition; }

int FindBufferPosition(int ProPos) {

int TempPos;

for(int i=0;i

return TempPos; }

void Produce(void *p) {

DWORD wait_for_semaphore,wait_for_mutex,m_delay; int m_serial;

m_serial=((ThreadInfo*)(p))->serial;

m_delay=( DWORD)(((ThreadInfo*)(p))->delay *INTE_PER_SEC); Sleep(m_delay);

printf(\

.

.

wait_for_semaphore=WaitForSingleObject(h_mutex,-1); int ProducePos=FindProducePosition(); ReleaseMutex(h_mutex);

printf(\ ProducePos);

Buffer_Critical[ProducePos]=m_serial;

printf(\

printf(\ ReleaseSemaphore(h_Semaphore[m_serial],n_Thread,NULL); }

void Consume(void *p) {

DWORD wait_for_semaphore,m_delay; int m_serial,m_requestNum;

int m_thread_request[MAX_THREAD_NUM];

m_serial=((ThreadInfo*)(p))->serial;

m_delay=(DWORD)(((ThreadInfo*)(p))->delay *INTE_PER_SEC); m_requestNum=((ThreadInfo*)(p))->n_request; for(int i=0;i

m_thread_request[i]=((ThreadInfo*)(p))->thread_request[i]; Sleep(m_delay);

for(i=0;i

printf(\wait_for_semaphore=WaitForSingleObject(h_Semaphore[m_thread_request[i]],-1);

int BufferPos=FindBufferPosition(m_thread_request[i]);

EnterCriticalSection(&PC_Critical[BufferPos]);

printf(\ ((ThreadInfo*)(p))->thread_request[i]=-1; if(!IfInOtherRequest(m_thread_request[i])){ Buffer_Critical[BufferPos]=-1;

printf(\ReleaseSemaphore(empty_semaphore,1,NULL); } else {

.

.

printf(\}

LeaveCriticalSection(&PC_Critical[BufferPos]); } }

5.实验运行结果:

其中的实验数据是: 3 1 p 5 2 p 4 3 p 2

.

.

4 c 3 1 3 2

6.实验结果分析:

(1)在每个程序中需要先做P,后做V,二者要成对出现,夹在二者中间的代码段就是该进程的临界区。 (2)对同步信号量full和empty的P,V操作同样必须成对出现,但它们分别位于不同的程序中。 (3)无论在生产者进程中还是消费者进程中,两个P操作的次序不能颠倒:应先执行同步信号量的P操作,然后执行互斥信号量的P操作。否则可能造成进程死锁。

六、实验总结

1.通过本次实验,了解到生产者/消费者问题是一个经典的进程同步问题,以及在其中使用信号量机制,生产者与消费者问题要求我们设计在同一个进程地址空间内执行的两个线程。

2.通过本次实验,加深了我对操作系统中多线程机制的理解和认识,更让我认识到知识的掌握,仅靠学习理论知识是远远不够的,要与实际动手操作相结合才能更好地理解和分析问题。

3.通过本次实验,发现自己在编程上及一些函数的认识仍存在较大的问题,日后会不断加深各方面知识的学习,弥补自己的不足。

.