用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - c++代码库

生产者-消费者

2012-10-13 作者: feng举报

[c++]代码库

#include <windows.h>
#include <stdio.h>
#include <iostream>

bool g_continue=true;
DWORD  WINAPI Thread1(LPVOID lpPara); //线程1
DWORD  WINAPI Thread2(LPVOID lpPara); //线程2
struct buffer
{
	int bufferpd;  //存放产品 
	bool bufferzt; //状态 
};
HANDLE hmutex=CreateMutex(NULL,FALSE,"readcoutmtx");
HANDLE hfull=CreateSemaphore(NULL,0,10,	"bufferfull");
HANDLE hempty=CreateSemaphore(NULL,10,10,"butterhempty");

int main()
{
	HANDLE hThread1, hThread2; //两个线程的handle
	DWORD ThreadId1, ThreadId2; //两个线程的线程ID
	hThread1 = CreateThread(NULL,0,Thread1,NULL,0,&ThreadId1);  //创建线程1
	if(hThread1 == NULL)
		return -1;
	hThread2 = CreateThread(NULL,0,Thread2,NULL,0,&ThreadId2);  //创建线程2
	if(hThread2 == NULL)
		return -1;

    if(getchar()) //按回车后终止程序运行
		g_continue = false;
    system("pause");
}

//线程1执行的代码
buffer bf[10];
DWORD  WINAPI Thread1(LPVOID lpPara)
{
    int n=0,a=0;
	while(g_continue)
	{
		WaitForSingleObject(hempty,INFINITE);
		WaitForSingleObject(hmutex,INFINITE);
		bf[n].bufferzt=1;
        bf[n].bufferpd=++n;
        std::cout<<"生产者将产品"<<n<<"放入缓冲单元"<<n-1<<",缓冲队列当前状态为:"<<std::endl;
        std::cout<<"缓冲单元编号"<<"   产品编号"<<"   缓冲单元状态"<<std::endl;
        for(a=0;a<10;a++)
             std::cout<<"       "<<a<<"           "<<bf[a].bufferpd<<"          "<<bf[a].bufferzt<<std::endl;  
		n=n%10;
		Sleep(200);	//睡眠,让出CPU使用权
		ReleaseMutex(hmutex);
		ReleaseSemaphore(hfull,1,NULL);
    }
	return 0;
}


//线程2执行的代码
DWORD  WINAPI Thread2(LPVOID lpPara)
{
	int spend=0,a=0;
    while(g_continue)
	{
        WaitForSingleObject(hfull,INFINITE);
		WaitForSingleObject(hmutex,INFINITE);
		Sleep(200);   //睡眠,让出CPU使用权
        bf[spend].bufferpd=0;
        bf[spend].bufferzt=0;
        std::cout<<"消费者从冲单元"<<spend<<"将产品"<<spend+1<<"取出,缓冲队列当前状态为:"<<std::endl;
        std::cout<<"缓冲单元编号"<<"   产品编号"<<"   缓冲单元状态"<<std::endl;
        for(a=0;a<10;a++)
             std::cout<<"        "<<a<<"          "<<bf[a].bufferpd<<"          "<<bf[a].bufferzt<<std::endl;  
        spend=(spend+1)%10;
		ReleaseMutex(hmutex);
		ReleaseSemaphore(hempty,1,NULL);
    }
    return 0;
}   




网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...