Win32 API进行程序设计具有很多优点:应用程序执行代码小,运行效率高,但是他要求程序员编写的代码较多,且需要管理所有系统提供给程序的资源,要求程序员对Windows系统内核有一定的了解,会占用程序员很多时间对系统资源进行管理,因而程序员的工作效率降低。
简单实例
1 #include <iostream> 2 #include <windows.h> 3 using namespace std; 4 5 DWORD WINAPI ThreadProc1(LPVOID lpParameter) 6 { 7 8 for (int i = 0; i < 10; i++) 9 { 10 cout << "我是子线程1" << " " << i << endl; 11 } 12 return 0; 13 } 14 15 DWORD WINAPI ThreadProc2(LPVOID lpParameter) 16 { 17 cout << "我是子线程2" << endl; 18 return 0; 19 } 20 21 void main() 22 { 23 HANDLE hThread1,hThread2; 24 hThread1 = CreateThread(NULL, NULL, ThreadProc1, NULL, NULL, NULL); 25 hThread2 = CreateThread(NULL, NULL, ThreadProc2, NULL, NULL, NULL); 26 WaitForSingleObject(hThread1, INFINITE); //同步 27 WaitForSingleObject(hThread2, INFINITE); 28 cout << "我是主线程" << endl; 29 while (1); 30 }
含参数传递的实例
1 #include <iostream> 2 #include <windows.h> 3 using namespace std; 4 class DATA 5 { 6 public: 7 int a=0; 8 int b=0; 9 int c=0; 10 public: 11 DATA() 12 { 13 a = 1; b = 2; c = 3; 14 } 15 DATA(int aa, int bb, int cc) 16 { 17 a = aa; 18 b = bb; 19 c = cc; 20 } 21 }; 22 23 DWORD WINAPI ThreadProc1(LPVOID lpParameter) 24 { 25 DATA* d = (DATA*)lpParameter; 26 27 for (int i = 0; i < 10; i++) 28 { 29 cout << "我是子线程1" << " " << i << endl; 30 cout << d->a << endl; 31 } 32 return 0; 33 } 34 35 DWORD WINAPI ThreadProc2(LPVOID lpParameter) 36 { 37 cout << "我是子线程2" << endl; 38 return 0; 39 } 40 41 void main() 42 { 43 HANDLE hThread1, hThread2; 44 DATA *d = new DATA(10,20,30); 45 hThread1 = CreateThread(NULL, NULL, ThreadProc1, d, NULL, NULL); 46 hThread2 = CreateThread(NULL, NULL, ThreadProc2, NULL, NULL, NULL); 47 WaitForSingleObject(hThread1, INFINITE); 48 WaitForSingleObject(hThread2, INFINITE); 49 cout << "我是主线程" << endl; 50 while (1); 51 }
LPVOID是个传递参数的玩意,无实际类型 ,大致就是这么用。