首页 > 代码库 > 前置++和后置++的区别
前置++和后置++的区别
今天看了一下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);现在要加上这条语句才可以。
前置++和后置++的区别
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。