作者:bw32dts | 来源:互联网 | 2023-09-24 07:44
我们进行Windows编程编写多线程程序的时候经常需要用到线程同步,我们来实现用Event同步线程。请见代码注释与实例讲解。[cpp]viewplaincopy*头文件*#incl
我们进行Windows编程编写多线程程序的时候经常需要用到线程同步,我们来实现用Event同步线程。
请见代码注释与实例讲解。
[cpp] view plain copy
-
- #include
- #include
-
- #define NUMTHREADS 3
- #define BUFFER_SIZE 16
- #define FOR_TIMES 5
-
- HANDLE hWriteEvent[NUMTHREADS];
- HANDLE hReadEvents[NUMTHREADS];
- BYTE lpSharedBuffer[16] = {0};
-
- void MultiEvents(void);
- VOID WriteToBuffer(VOID);
- DWORD WINAPI ThreadFunction(LPVOID lpParam);
-
-
-
-
-
-
-
- int main()
- {
- MultiEvents();
- }
-
-
-
-
-
-
-
- void MultiEvents(void)
- {
- HANDLE hThread;
- DWORD i;
-
-
- for(i = 0; i < NUMTHREADS; i++)
- {
-
- hWriteEvent[i] = CreateEvent(
- NULL,
- FALSE,
- FALSE,
- NULL
- );
-
- if (hWriteEvent[i] == NULL)
- {
- printf("CreateEvent failed (%d)\n", GetLastError());
- return;
- }
-
- hReadEvents[i] = CreateEvent(
- NULL,
- FALSE,
- FALSE,
- NULL);
- if (hReadEvents[i] == NULL)
- {
- printf("CreateEvent failed (%d)\n", GetLastError());
- return;
- }
-
- hThread = CreateThread(NULL, 0,
- ThreadFunction,
- (LPVOID)i,
- 0, NULL);
- if (hThread == NULL)
- {
- printf("CreateThread failed (%d)\n", GetLastError());
- return;
- }
- }
- WriteToBuffer();
- }
-
-
-
-
-
-
-
-
- VOID WriteToBuffer(VOID)
- {
- DWORD dwWaitResult, j,i;
-
- for (j = 0; j < FOR_TIMES; j++)
- {
- Sleep(rand()%100);
-
- wsprintf(lpSharedBuffer,"shared %d",j);
-
-
- for(i=0; i
- {
- if (! SetEvent(hWriteEvent[i]) )
- {
- printf("SetEvent failed (%d)\n", GetLastError());
- return;
- }
- }
-
- dwWaitResult = WaitForMultipleObjects(
- NUMTHREADS,
- hReadEvents,
- TRUE,
- INFINITE);
-
- if (dwWaitResult != WAIT_OBJECT_0)
- {
- printf("Wait error: %d\n", GetLastError());
- ExitProcess(0);
- }
- }
- }
-
-
-
-
-
-
-
- DWORD WINAPI ThreadFunction(LPVOID lpParam)
- {
- DWORD dwWaitResult;
- BYTE lpRead[16];
- DWORD j = 0;
- DWORD dwThreadIndex = (DWORD)lpParam;
-
- for(; j
- {
-
- dwWaitResult = WaitForSingleObject(
- hWriteEvent[dwThreadIndex],
- INFINITE);
- switch (dwWaitResult)
- {
- case WAIT_OBJECT_0:
- Sleep(rand()%10);
- CopyMemory(lpRead,lpSharedBuffer,16);
- break;
-
- default:
- printf("Wait error: %d\n", GetLastError());
- ExitThread(0);
- }
-
- if (! SetEvent(hReadEvents[dwThreadIndex]) )
- {
- printf("SetEvent failed (%d)\n", GetLastError());
- return 0;
- }
-
- printf("线程 %u\t第 %d 次读,内容:%s\n",
- dwThreadIndex,j,(LPSTR)lpRead);
- }
- return 1;
- }