Threads(Chapter 3 of Concurrent Programming on Windows)

1 #include <stdio.h>
2 #include <windows.h>
3
4 DWORD WINAPI MyThreadStart(LPVOID);
5
6 int main(int argc, wchar_t * argv[])
7 {
8 HANDLE hThread;
9 DWORD dwThreadId;
10
11 hThread = CreateThread(NULL,
12 0,
13 &MyThreadStart,
14 "Hello World",
15 0,
16 &dwThreadId);
17
18 if(!hThread)
19 {
20 fprintf(stderr, "Thread creation failed: %d\r\n", GetLastError());
21 return -1;
22 }
23
24 printf("%d: Created thread %x (ID %d)\r\n", GetCurrentThreadId(), hThread, dwThreadId);
25
26 WaitForSingleObject(hThread, INFINITE);
27 DWORD dwExitCode;
28 GetExitCodeThread(hThread, &dwExitCode);
29 printf("%d: Thread exited: %d\r\n", GetCurrentThreadId(), dwExitCode);
30 CloseHandle(hThread);
31
32 return 0;
33 }
34
35 DWORD WINAPI MyThreadStart(LPVOID lpParameter)
36 {
37 printf("%d: Running: %s\r\n", GetCurrentThreadId(), reinterpret_cast<char *>(lpParameter));
38 return 0;
39 }
2 #include <windows.h>
3
4 DWORD WINAPI MyThreadStart(LPVOID);
5
6 int main(int argc, wchar_t * argv[])
7 {
8 HANDLE hThread;
9 DWORD dwThreadId;
10
11 hThread = CreateThread(NULL,
12 0,
13 &MyThreadStart,
14 "Hello World",
15 0,
16 &dwThreadId);
17
18 if(!hThread)
19 {
20 fprintf(stderr, "Thread creation failed: %d\r\n", GetLastError());
21 return -1;
22 }
23
24 printf("%d: Created thread %x (ID %d)\r\n", GetCurrentThreadId(), hThread, dwThreadId);
25
26 WaitForSingleObject(hThread, INFINITE);
27 DWORD dwExitCode;
28 GetExitCodeThread(hThread, &dwExitCode);
29 printf("%d: Thread exited: %d\r\n", GetCurrentThreadId(), dwExitCode);
30 CloseHandle(hThread);
31
32 return 0;
33 }
34
35 DWORD WINAPI MyThreadStart(LPVOID lpParameter)
36 {
37 printf("%d: Running: %s\r\n", GetCurrentThreadId(), reinterpret_cast<char *>(lpParameter));
38 return 0;
39 }