创建两个子线程,子线程1循环 10 次,接着子线程2循环 10 次,接着又回到子线程1循环 10 次,接着再回到2又循环 10 次,如此循环50次,试写出代码。
(注:在写本篇学习笔记时,本人学习和参考了网络文章,并做了借鉴,感谢各位前辈的分享。如果本文对您有所帮助,您可以随意分享,如果发现文中有误,也请指教,谢谢。本文用到的调试工具:Microsoft Visual Studio 10,操作系统:Windows 7)
代码实现为:
#include "stdafx.h"
#include "process.h"
#include "windows.h"
static int gCount=0;
const int gSum=5;//总循环次数
const int gSleepTimes=100;
const int gEvyCount=3;
HANDLE g_hEventId[2];// 用于子线程之间的同步
HANDLE g_hFthEventId;// 用于父子线程的同步
CRITICAL_SECTION g_csThreadCode;
unsigned int __stdcall ThreadFunc(LPVOID pM)
{
int i=0;
int * w=(int *)pM;
HANDLE h1;
HANDLE h2;
if (*w==0)
{
h1=g_hEventId[0];
h2=g_hEventId[1];
}
else
{
h1=g_hEventId[1];
h2=g_hEventId[0];
}
printf("子线程[%d]启动\n",GetCurrentThreadId());
SetEvent(g_hFthEventId);
while(TRUE)
{
WaitForSingleObject(h1, INFINITE);
EnterCriticalSection(&g_csThreadCode);
if (h1==g_hEventId[0])
{
gCount++;
}
if (gCount>gSum)
{
LeaveCriticalSection(&g_cs