天天看点

多线程-3

#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;
}      

运行结果:

多线程-3

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;
}      
多线程-3