现在的位置: 首页 > 综合 > 正文

生产者和消费者

2013年05月16日 ⁄ 综合 ⁄ 共 1255字 ⁄ 字号 评论关闭

好几天没有写日记了,我觉得我该补上。

刚好这几天在帮人家写几个程序,我就复习吧。

今天写个生产者和消费者,温习下多线程和互斥变量的用法吧。

在操作系统课程内有临界区的说法,在windows下存在类型CRITICAL_SECTION,这就是个互斥变量,我一般就喜欢叫做锁,虽然这样叫有点欠妥~~~~~~~~~~

CRITICAL_SECTION 使用步骤分3步。

第一:初始化该变量-----------------------------InitializeCriticalSection(LPCRITICAL_SECTION);

第二:使用该变量进行互斥访问-----------------EnterCriticalSection,LeaveCriticalSection

第三:在结束了对该变量的使用后,别忘记删除该变量哦。DeleteCriticalSection

 

附代码:

 

CRITICAL_SECTION xLock;
int ntest = 0;
int nStore[20];

 

 

DWORD WINAPI Producer(LPVOID param)
{
 int i=0;
 while(i<20 && ntest>=0 )
 {
  if(ntest<20)//存储空间未满
  {
   EnterCriticalSection(&xLock);
   nStore[ntest++] = 1;//存储
   cout<<"生产者"<<endl;
   LeaveCriticalSection(&xLock);
   i++;
   Sleep(8);
  }

 }
 return 0;
}

 

 

DWORD WINAPI Consumer(LPVOID param)
{
 int i=0;
 while (i<20 )
 {
  if (ntest>0)//仓库仍有货物
  {
   EnterCriticalSection(&xLock);
   ntest--;//消费
   cout<<"消费者"<<endl;
   i++;
   LeaveCriticalSection(&xLock);
   Sleep(16);
  }

 }
 return 0;

 

 

 

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
 int nRetCode = 0;
 HANDLE hThread[2];

 InitializeCriticalSection(&xLock);
 hThread[0] = CreateThread(NULL,0,Producer,NULL,0,NULL);
 hThread[1] = CreateThread(NULL,0,Consumer,NULL,0,NULL);
 WaitForMultipleObjects(2, hThread, TRUE, INFINITE);
  for (int i=0;i<2;i++)
 {
  CloseHandle(hThread[i]);
 }

DeleteCriticalSection(&xLock);
 return nRetCode;
}

抱歉!评论已关闭.