/* * Worker.cpp * * Sample code for "Multithreading Applications in Win32" * This is from Chapter 14, Listing 14-3 * * Demonstrate using worker threads that have * their own message queue but no window. */ #define WIN32_LEAN_AND_MEAN#include <stdio.h>#include <stdlib.h>#include <windows.h>#include <process.h>#include <string.h>#include "MtVerify.h"unsigned WINAPI ThreadFunc(void* p);HANDLE ghEvent;#define WM_JOB_PRINT_AS_IS WM_APP + 0x0001#define WM_JOB_PRINT_REVERSE WM_APP + 0x0002#define WM_JOB_PRINT_LOWER WM_APP + 0x0003#define WM_LEIWEIWM_APP + 0x0004int main(VOID) { HANDLE hThread; unsigned tid; // Give the new thread something to talk // to us with.//建立手動事件 ghEvent = CreateEvent(NULL, TRUE, FALSE, NULL);unsigned CurrentId = GetCurrentThreadId();UNREFERENCED_PARAMETER(CurrentId); hThread = (HANDLE)_beginthreadex(NULL, 0, ThreadFunc, 0, 0, &tid ); MTVERIFY(hThread); // This thread has to wait for the new thread // to init its globals and msg queue. WaitForSingleObject(ghEvent, INFINITE);//等待事件有訊號 // The only place in the book we get to use // the thread ID!//strdup 調用的是malloc所以需要free char *szText = strdup("Thank you for buying this book.\n"); PostThreadMessage(tid, WM_JOB_PRINT_AS_IS, NULL, (LPARAM)szText); szText = strdup("Text is easier to read forward.\n"); PostThreadMessage(tid, WM_JOB_PRINT_REVERSE, NULL, (LPARAM)szText); szText = strdup("\nLOWER CASE IS FOR WHISPERING.\n"); PostThreadMessage(tid, WM_JOB_PRINT_LOWER, NULL, (LPARAM)szText);Sleep(4000);//給線程發訊息,退出PostThreadMessage(tid,WM_QUIT,0,0); WaitForSingleObject(hThread, INFINITE);//等待線程退出,然後關閉控制代碼 CloseHandle(hThread);system("pause"); return 0;} VOID CALLBACK TimerFunc( HWND hwnd, // handle of window for timer messages UINT uMsg, // WM_TIMER message UINT idEvent, // timer identifier DWORD dwTime ) // current system time{//取消編譯器的警告,沒有引用的變數 UNREFERENCED_PARAMETER(hwnd); UNREFERENCED_PARAMETER(uMsg);printf("onTimer function\n"); // PostThreadMessage(GetCurrentThreadId(), WM_QUIT,0,0);unsigned id = GetCurrentThreadId();PostThreadMessage(id, WM_LEIWEI,0,0);} /* * Call a function to do something that terminates * the thread with ExitThread instead of returning. */unsigned WINAPI ThreadFunc(LPVOID n){ UNREFERENCED_PARAMETER(n); MSG msg; // This creates the message queue.//建立一個訊息佇列 PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE);//設定事件有啟用 SetEvent(ghEvent); // We'll run for two seconds SetTimer(NULL, NULL, 500, (TIMERPROC)TimerFunc); while (GetMessage(&msg, NULL, 0, 0)) { char *psz = (char *)msg.lParam; switch(msg.message) { case WM_JOB_PRINT_AS_IS: printf("%s", psz); free(psz); break; case WM_JOB_PRINT_REVERSE: printf("%s", strrev(psz)); free(psz); break; case WM_JOB_PRINT_LOWER: printf("%s", _strlwr(psz)); free(psz); break;case WM_LEIWEI:printf("timer:............\n");break; default:printf("message id=%0X\n",msg.message); DispatchMessage(&msg); } } return 0;}