多线程-3

来源:互联网 发布:东风天锦配件淘宝 编辑:程序博客网 时间:2024/04/28 20:25
#include <windows.h>#include <iostream.h>//using namespace std;DWORD WINAPI Fun1Proc(  LPVOID lpParameter   // thread data);void main(){    HANDLE hThread1;//线程的句柄    hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);    CloseHandle(hThread1);    cout<<"main thread is running!"<<endl;    Sleep(100);//主线程休眠}DWORD WINAPI Fun1Proc(  LPVOID lpParameter   // thread data){    cout<<"thread1 is running"<<endl;    return 0;}

运行结果:


Sleep函数暂停主线程,使之放弃执行权力,时间片给了线程1,使线程1运行

加上循环后:

#include <windows.h>#include <iostream.h>//using namespace std;DWORD WINAPI Fun1Proc(  LPVOID lpParameter   // thread data);int index=0;void main(){    HANDLE hThread1;//线程的句柄    hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);    CloseHandle(hThread1);    while(index++<100)       cout<<"main thread is running!"<<endl;   // Sleep(100);//主线程休眠}DWORD WINAPI Fun1Proc(  LPVOID lpParameter   // thread data){    while(index++<100)       cout<<"thread1 is running"<<endl;    return 0;}

线程交替运行,时间片不同


0 0
原创粉丝点击