前置++和后置++的区别
2014-10-12 20:15
183 查看
今天看了一下windows c中多线程编程,写了一小段程序。死活跑出结果,先贴一下我的代码
while循环中,因为i = 0为初始条件,后置的i ++会先判断条件,i = 0不会执行while语句。将i++变成++i就好了
这里就会每秒输出,一条信息
ps:
#include <windows.h> #include <iostream.h> #include <string> using namespace std; DWORD WINAPI countThread1(LPVOID argv);//声明一个线程函数 DWORD WINAPI countThread2(LPVOID argv); int main(){ //创建两个线程 HANDLE handle1 = CreateThread(NULL, 0, countThread1, NULL, 0, NULL); WaitForSingleObject(handle1, INFINITE); return 0; } //下面是两个线程函数 DWORD WINAPI countThread1(LPVOID argv){ int i = 0; cout<<"i am in"<<endl; while(i++){ //这里开始没看出来有错,开始没注意这段代码,以为是main里面出错了。后面输出i am in我知道这段代码有问题了 if(10 == i) ExitThread(0); cout<<"this is thread2 and i = "<<i<<endl; Sleep(1000); } return 0; } DWORD WINAPI countThread2(LPVOID argv){ int i = 0; while(i++){ if(10 == i) ExitThread(0); cout<<"this is thread2 and i = "<<i<<endl; Sleep(1000); } return 0; }
while循环中,因为i = 0为初始条件,后置的i ++会先判断条件,i = 0不会执行while语句。将i++变成++i就好了
#include <windows.h> #include <iostream.h> #include <string> using namespace std; DWORD WINAPI countThread1(LPVOID argv);//声明一个线程函数 DWORD WINAPI countThread2(LPVOID argv); int main(){ //创建两个线程 // int i = 0; // while(i < 50){ HANDLE handle1 = CreateThread(NULL, 0, countThread1, NULL, 0, NULL); // HANDLE handle2 = CreateThread(NULL, 0, countThread2, NULL, 0, NULL); WaitForSingleObject(handle1, INFINITE); // WaitForSingleObject(handle2, INFINITE); //CreateThread(NULL, 0, countThread2, NULL, 0, NULL); //Sleep(50000); // } return 0; } //下面是两个线程函数 DWORD WINAPI countThread1(LPVOID argv){ int i = 0; cout<<"i am in"<<endl; while(++i){ if(10 == i) ExitThread(0); cout<<"this is thread2 and i = "<<i<<endl; Sleep(1000); } return 0; } DWORD WINAPI countThread2(LPVOID argv){ int i = 0; while(++i){ if(10 == i) ExitThread(0); cout<<"this is thread2 and i = "<<i<<endl; Sleep(1000); } return 0; }
这里就会每秒输出,一条信息
ps:
WaitForSingleObject(handle1, INFINITE);现在要加上这条语句才可以。
相关文章推荐
- 前置++和后置++的区别
- (转)前置++和后置++的区别
- c++ 前置++与后置++的区别
- C++中前置++和后置++的区别
- (转)前置++和后置++的区别
- [C++] 前置++和后置++的区别
- C语言中前置++和后置++的区别
- 前置++和后置++的区别
- (1.1.22)前置++和后置++的区别
- C++ 递增运算符:前置++和后置++的区别
- C语言中的前置++和后置++的区别
- 前置++和后置++的区别
- 前置++和后置++的区别
- 前置++和后置++的区别
- C语言中的前置++和后置++的区别
- c++ 前置++与后置++的区别
- 前置++为什么比后置++效率高
- C++前置和后置运算符的区别
- 对于C++中的前置++和后置++的看法
- 前置++为什么比后置++效率更高?