码迷,mamicode.com
首页 > 其他好文 > 详细

前置++和后置++的区别

时间:2014-10-12 23:38:18      阅读:362      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   for   sp   

今天看了一下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 }

bubuko.com,布布扣

这里就会每秒输出,一条信息

ps:

WaitForSingleObject(handle1, INFINITE);现在要加上这条语句才可以。

前置++和后置++的区别

标签:style   blog   http   color   io   os   ar   for   sp   

原文地址:http://www.cnblogs.com/luckygxf/p/4020975.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!