惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
Check Point Blog
Microsoft Security Blog
Microsoft Security Blog
aimingoo的专栏
aimingoo的专栏
V
V2EX
博客园 - 【当耐特】
T
Tailwind CSS Blog
Apple Machine Learning Research
Apple Machine Learning Research
量子位
MyScale Blog
MyScale Blog
Hugging Face - Blog
Hugging Face - Blog
大猫的无限游戏
大猫的无限游戏
The Cloudflare Blog
月光博客
月光博客
I
InfoQ
WordPress大学
WordPress大学
Martin Fowler
Martin Fowler
T
The Blog of Author Tim Ferriss
爱范儿
爱范儿
小众软件
小众软件
罗磊的独立博客
Recent Announcements
Recent Announcements
Blog — PlanetScale
Blog — PlanetScale
J
Java Code Geeks
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC

博客园 - 不再专注于.net技术

嵌入式c/C++ 多线程专题3 - 不再专注于.net技术 - 博客园 多线程同步问题专题(1) TCP/IP卷一(4) TCP/IP卷一(3) TCP/IP卷一(2) TCP/IP卷一(1) Net Programming 设备坐标 删除内存树结构的时候,千万注意内存泄漏问题,采用递归比较简单。 投资收益 The Strategy Pattern Com+ ?? Learning Bridge pattern. debian linux 树结构的遍历与建立树 初始化COM GNU Debian Linux学习 vc调用vb DLL方法
多线程调度专题2 - 不再专注于.net技术 - 博客园
不再专注于.net技术 · 2006-03-13 · via 博客园 - 不再专注于.net技术

UINT ThreadProc3(LPVOID pParam)
{
 WaitForSingleObject(hEvent[0],INFINITE);
 for (int i = 0; i < 10; i++)
 {
  g_cArray[i] = 'a';
  Sleep(1);
 }
     TRACE("Second  T3");
 SetEvent(hEvent[0]);
 SetEvent(hEvent[2] );

 return 0;
}
UINT ThreadProc4(LPVOID pParam)
{
 WaitForSingleObject(hEvent[1],INFINITE);
 for (int i = 0; i < 10; i++)
 {
  g_cArray[10-i-1] = 'b';
  Sleep(1);
 }
 TRACE("First ---T4");
 SetEvent(hEvent[1]);

 SetEvent(hEvent[0]);
 

 return 0;
}
UINT ThreadProc5(LPVOID pParam)
{
 WaitForSingleObject(hEvent[2],INFINITE);
 for (int i = 0; i < 10; i++)
 {
  g_cArray[10-i-1] = 'c';
  Sleep(1);
 }
    TRACE("Third  T5"); 
 SetEvent(hEvent[2]);
 
 SetEvent(hEvent[3]);
   
 return 0;
}

//Testing
void CTestCritionDlg::OnButton2()
{
 hEvent[0] = CreateEvent(NULL, FALSE, FALSE, NULL);
 hEvent[1] = CreateEvent(NULL, FALSE, FALSE, NULL);
 hEvent[2] = CreateEvent(NULL, FALSE, FALSE, NULL);

 SetEvent(hEvent[1]);
 AfxBeginThread(ThreadProc4, NULL);
 AfxBeginThread(ThreadProc3, NULL);
 AfxBeginThread(ThreadProc5, NULL); 
 DWORD dwRet2 = WaitForMultipleObjects(4, hEvent, TRUE, INFINITE);
 if (dwRet2 == WAIT_OBJECT_0)
 {
CString sResult = CString(g_cArray);
AfxMessageBox(sResult);
 }

}

解释:
开出三个线程,控制线程按次序等待进行调度,从这个例子中可以理解生产者和消费者问题。
程序一旦进入运行,必然按这个次序进行调度,但如果调用AfxMessageBox,因为这个是系统开销,弹出的对话框
次序不一定一致,这点需要注意。
解决办法:可以采用延时机制每个线程中SetEvent前加上延时。