使用_beginthreadex 来创建线程比CreateThread 更加的安全,但是_beginthreadex 需要传入的参数和CreateThread并不是一样的,但基本相同,只需要做一些转换,线程的同步采用两种方式实现,一是采用关键代码段(已注释)和事件内核对象来实现。 以下是实现:
#include "stdafx.h"
#include "windows.h"
#include <PROCESS.H>
#include <stddef.h>
#include <iostream.h>
int g_nCount = 0;
typedef unsigned (__stdcall *PTHREAD_START) (void*);
//CRITICAL_SECTION gcs;
HANDLE hEvent = NULL;
DWORD WINAPI ThreadProc1(PVOID *pData)
{
while (g_nCount < 100)
{
// EnterCriticalSection(&gcs);
WaitForSingleObject(hEvent,50000);
g_nCount++;
cout << "thread1" << endl;
cout << g_nCount << endl;
SetEvent(hEvent);
Sleep(1);
// LeaveCriticalSection(&gcs);
}
return 0;
}