您的位置:首页 > 其它

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

2014-10-12 20:15 183 查看
今天看了一下windows c中多线程编程,写了一小段程序。死活跑出结果,先贴一下我的代码

#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);现在要加上这条语句才可以。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: