windows C++ 互相等待线程同步示例
开发中遇到线程同步问题,可抽象为如下模型:
1、主线程的继续执行的前提是子线程的变量已经初始化完毕。
2、子线程待主线程执行完毕后继续执行后续的初始化操作。
重复1,2执行……直到通信结束。
如下图所示:
源码(VS2010编译、运行通过)
#include "stdafx.h"
#include <iostream>
using namespace std;
#include <windows.h>
const char* g_pszEventName = "GLOBAL/MY_EVENT"; //事件对象的名称
HANDLE g_hSetTaskIdEvent = NULL; //全局Event事件
const int g_iMaxRunCnt = 50; //最大的运行次数.
/*
**@brief:模拟线程函数。
**@param:LPVOID pParam 线程参数,未使用(可传递结构体指针等)
**@return 0,ok; 其他代表异常退出。
*/
UINT RecvDataThreadProc(LPVOID pParam)
{
cout << "The RecvDataThreadProc() is Running!" << endl;
int nThreadCnt = 0;
while(nThreadCnt < g_iMaxRunCnt)
{
printf("[Thread] The TaskId already Setted! RunCnt = %d\n", nThreadCnt++);
SetEvent(g_hSetTaskIdEvent); //触发,主线程可以运行.
WaitForSingleObject(g_hSetTaskIdEvent, INFINITE);
}
return 0;
}
/*
**@brief:主线程和副线程交替运行。
**
**
*/
int _tmain(int argc, _TCHAR* argv[])
{
// 启动一个处理线程
DWORD dwThreadId = 0;
HANDLE hRecvThread = CreateThread(NULL, //Choose default security
0, //Default stack size
(LPTHREAD_START_ROUTINE)&RecvDataThreadProc,//Routine to execute
(LPVOID) NULL, //Thread parameter
0, //Immediately run the thread
&dwThreadId //Thread Id
);
if (NULL == hRecvThread)
{
printf("CreateThread Failed! ErrCode: %d\n", GetLastError());
return(1);
}
else
{
printf("CreateThread OK!\n");
}
CloseHandle(hRecvThread);
//1.创建命名的事件对象,自动且初始化为无信号状态
g_hSetTaskIdEvent= CreateEvent(NULL, FALSE, FALSE, (LPCWSTR)(g_pszEventName));
int iErrorCode = GetLastError();
if (ERROR_ALREADY_EXISTS == iErrorCode)
{
printf("[Process]CreateEvent() the object is already exist!\n");
}
else if (NULL == g_hSetTaskIdEvent)
{
printf("[Process] CreateEvent() Error, Errorcode: %d\n", iErrorCode);
}
else
{
printf("[Process] CreateEvent() Success!\n");
}
unsigned int nRunCnt = 0;
while(nRunCnt < g_iMaxRunCnt)
{
bool bRunNext = false; //初始置为false,不可以执行下面的操作。
//等待信号触发
DWORD dwRst = WaitForSingleObject(g_hSetTaskIdEvent, INFINITE);
switch(dwRst)
{
case WAIT_OBJECT_0:
// The process terminated.
printf("[Process]The state of the specified object is signaled.\n");
bRunNext = true;
break;
case WAIT_TIMEOUT:
// The process did not terminate within the given milliseconds.
printf("[Process]The time-out interval elapsed, and the object‘s state is nonsignaled.\n");
break;
case WAIT_FAILED:
// Bad call to function (invalid handle?)
printf("[Process]WAIT_FAILED, ErrCode: %d\n", GetLastError());
break;
}//end switch
//主线程运行后才可以执行下面的操作.
if (bRunNext)
{
printf("[Process] The Process() Next can running!, running cnt = %d\n", nRunCnt++);
}
SetEvent(g_hSetTaskIdEvent);
}
CloseHandle(g_hSetTaskIdEvent);
return 0;
}
本质抽象为:事件同步机制。和sunxin教程的火车票模型基本完全一致。
2014-3-20 pm23:47 思于家中床前
作者:铭毅天下
转载请标明出处,原文地址:http://blog.csdn.net/laoyang360/article/details/45646151
如果感觉本文对您有帮助,请点击‘顶’支持一下,您的支持是我坚持写作最大的动力,谢谢!
时间: 2024-11-05 16:33:57