天天看点

windows C++ 互相等待线程同步示例

如下图所示:

windows C++ 互相等待线程同步示例

源码(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);

 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");

 case WAIT_FAILED:

  // Bad call to function (invalid handle?)

  printf("[Process]WAIT_FAILED, ErrCode: %d\n", GetLastError());

 }//end switch

 //主线程运行后才可以执行下面的操作.

 if (bRunNext)

  printf("[Process] The Process() Next can running!, running cnt = %d\n", nRunCnt++);

 }

 SetEvent(g_hSetTaskIdEvent);

CloseHandle(g_hSetTaskIdEvent);

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

本质抽象为:事件同步机制。和sunxin教程的火车票模型基本完全一致。

【反思】

1.当遇到复杂的逻辑,如:通信复杂、调用混乱,一定要先把思路梳理清楚;

2.当复杂的程序无法进行全局测试的时候,可以考虑抽象模型为小Demo,通过小Demo测试大致框架逻辑的准确性。