天天看點

前置++和後置++的差別

今天看了一下windows c中多線程程式設計,寫了一小段程式。死活跑出結果,先貼一下我的代碼

1 #include <windows.h>
 2 #include <iostream.h>
 3 #include <string>
 4 
 5 using namespace std;
 6 
 7 DWORD WINAPI countThread1(LPVOID argv);//聲明一個線程函數
 8 DWORD WINAPI countThread2(LPVOID argv);
 9 
10 int main(){
11     //建立兩個線程
14     HANDLE handle1 = CreateThread(NULL, 0, countThread1, NULL, 0, NULL);
16 
17     WaitForSingleObject(handle1, INFINITE);
24 
25 
26     return 0;
27 }
28 //下面是兩個線程函數
29 DWORD WINAPI countThread1(LPVOID argv){
30     int i = 0;
31     cout<<"i am in"<<endl;
32     while(i++){      //這裡開始沒看出來有錯,開始沒注意這段代碼,以為是main裡面出錯了。後面輸出i am in我知道這段代碼有問題了
33         if(10 == i)
34             ExitThread(0);
35         cout<<"this is thread2 and i = "<<i<<endl;
36         Sleep(1000);
37     }
38 
39     return 0;
40 }
41 DWORD WINAPI countThread2(LPVOID argv){
42     int i = 0;
43     while(i++){
44         if(10 == i)
45             ExitThread(0);
46         cout<<"this is thread2 and i = "<<i<<endl;
47         Sleep(1000);
48     }
49     return 0;
50 }      

while循環中,因為i = 0為初始條件,後置的i ++會先判斷條件,i = 0不會執行while語句。将i++變成++i就好了

1 #include <windows.h>
 2 #include <iostream.h>
 3 #include <string>
 4 
 5 using namespace std;
 6 
 7 DWORD WINAPI countThread1(LPVOID argv);//聲明一個線程函數
 8 DWORD WINAPI countThread2(LPVOID argv);
 9 
10 int main(){
11     //建立兩個線程
12 //    int i = 0;
13 //    while(i < 50){
14     HANDLE handle1 = CreateThread(NULL, 0, countThread1, NULL, 0, NULL);
15 //    HANDLE handle2 = CreateThread(NULL, 0, countThread2, NULL, 0, NULL);
16 
17     WaitForSingleObject(handle1, INFINITE);
18 //    WaitForSingleObject(handle2, INFINITE);
19 
20             //CreateThread(NULL, 0, countThread2, NULL, 0, NULL);
21             //Sleep(50000);
22 
23 //    }
24 
25 
26     return 0;
27 }
28 //下面是兩個線程函數
29 DWORD WINAPI countThread1(LPVOID argv){
30     int i = 0;
31     cout<<"i am in"<<endl;
32     while(++i){
33         if(10 == i)
34             ExitThread(0);
35         cout<<"this is thread2 and i = "<<i<<endl;
36         Sleep(1000);
37     }
38 
39     return 0;
40 }
41 DWORD WINAPI countThread2(LPVOID argv){
42     int i = 0;
43     while(++i){
44         if(10 == i)
45             ExitThread(0);
46         cout<<"this is thread2 and i = "<<i<<endl;
47         Sleep(1000);
48     }
49     return 0;
50 }      

這裡就會每秒輸出,一條資訊

ps:

WaitForSingleObject(handle1, INFINITE);現在要加上這條語句才可以。