分类: C/C++
2008-03-14 15:35:44
//缓慢显示线程进行的结果 bool m_bSlow; //生产者线程 CProducerThread *m_pProducerThread; //消费者线程 CConsumerThread *m_pConsumerThread; //缓冲空的标志 CSemaphore* m_pSemaphoreEmpty; //缓冲满的标志 CSemaphore* m_pSemaphoreFull; CMutex *m_pMutex;//互斥信号量 添加两编辑框用类向导,相关的添加成员 //用来显示消费者取到的数据 CString m_sBufCSM; //显示生产者插入缓冲的数据 CString m_sBuf;2、创建用户界面线程,生产者和消费者线程。
CProducerThread::CProducerThread(void* hParent):m_pParentDlg(hParent) { } int CProducerThread::Run() { CP_CDlg *pDlg; pDlg=(CP_CDlg*)m_pParentDlg; CSingleLock mutexLock(pDlg->m_pMutex); for(int i=0;i3、启动线程:m_pSemaphoreEmpty->Lock(); mutexLock.Lock(); pDlg->m_sBuf.Format("%0.10d",i); mutexLock.Unlock(); pDlg->m_pSemaphoreFull->Unlock(); } return CWinThread::Run(); } CConsumerThread::CConsumerThread(void *pParent) :m_pParent(pParent) { } int CConsumerThread::Run() { CP_CDlg *pDlg; pDlg=(CP_CDlg*)this->m_pParent; char*pBuf; pBuf=this->m_Data; bool bSleep; for(int i=0;i m_pSemaphoreFull->Lock(); pDlg->m_pMutex->Lock(); sprintf(pBuf,pDlg->m_sBuf); bSleep=pDlg->m_bSlow ; pDlg->m_pMutex->Unlock(); pBuf+=10; if(pBuf>m_Data+CSM_BUF_COUNT-10) pBuf=m_Data; m_Data[CSM_BUF_COUNT]=0; pDlg->m_pMutex->Lock(); sprintf(pDlg->m_sBufCSM.GetBuffer(CSM_BUF_COUNT+10),m_Data); pDlg->m_pMutex->Unlock(); if (bSleep) Sleep(100); pDlg->m_pSemaphoreEmpty ->Unlock(); } return CWinThread::Run(); }
m_pSemaphoreFull =new CSemaphore(1,1); m_pSemaphoreEmpty =new CSemaphore(0,1); m_pMutex =new CMutex; this->m_bUpdateAuto =false; this->m_pProducerThread =new CProducerThread(this); this->m_pConsumerThread =new CConsumerThread(this); this->m_sBuf.Format("1234567890"); this->UpdateData(false); this->m_pProducerThread->CreateThread(CREATE_SUSPENDED); VERIFY(m_pProducerThread->SetThreadPriority(THREAD_PRIORITY_IDLE)); this->m_pConsumerThread->CreateThread(CREATE_SUSPENDED); VERIFY(m_pConsumerThread->SetThreadPriority(THREAD_PRIORITY_IDLE)); this->m_pProducerThread->ResumeThread(); this->m_pConsumerThread->ResumeThread();完