首先是一个普通的多线程样例。。
- //////////////////////////////////////////////////////////////////////////
- // CopyRight(c) 2009, YOYO, All Rights Reserved.
- // Author: LIN YiQian
- // Created: 2009/09/16
- // Describe: 多线程样例
- //////////////////////////////////////////////////////////////////////////
- #include <Windows.h>
- #include <iostream>
- using namespace std;
- DWORD WINAPI ThreadFun(LPVOID lpParameter);
- void main(void)
- {
- HANDLE hThread1 = CreateThread(NULL, 0, ThreadFun, new int(1), 0, NULL);
- HANDLE hThread2 = CreateThread(NULL, 0, ThreadFun, new int(2), 0, NULL);
- HANDLE hThread3 = CreateThread(NULL, 0, ThreadFun, new int(3), 0, NULL);
- CloseHandle(hThread1);
- CloseHandle(hThread2);
- CloseHandle(hThread3);
- Sleep(3000);
- return;
- }
- DWORD WINAPI ThreadFun(LPVOID lpParameter)
- {
- while (true)
- {
- printf("Thread %d is running../n", *((int*)lpParameter));
- Sleep(50);
- }
- }
下面是一个会出现同步问题的例子。。
- //////////////////////////////////////////////////////////////////////////
- // CopyRight(c) 2009, YOYO, All Rights Reserved.
- // Author: LIN YiQian
- // Created: 2009/09/16
- // Describe: 多线程出错样例 演示
- //////////////////////////////////////////////////////////////////////////
- #include <Windows.h>
- #include <iostream>
- using namespace std;
- DWORD WINAPI SellTickets(LPVOID lpParameter);
- int g_nTicket = 100;
- void main(void)
- {
- HANDLE hThread1 = CreateThread(NULL, 0, SellTickets, new int(1), 0, NULL);
- HANDLE hThread2 = CreateThread(NULL, 0, SellTickets, new int(2), 0, NULL);
- CloseHandle(hThread1);
- CloseHandle(hThread2);
- Sleep(3000);
- system("pause");
- return;
- }
- DWORD WINAPI SellTickets(LPVOID lpParameter)
- {
- while (g_nTicket > 0)
- {
- printf("Thread %d sells ticket: No.%d/n", *((int*)lpParameter), g_nTicket--);
- }
- return NULL;
- }
办法是使用内核对象的互斥信号量或事件对象,或使用用户工作区的临界区来解决。。详见下一篇日志。。