天天看點

多線程-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