/*************************
main.cpp
关于多线程的测试
*************************/
#include <windows.h>
#include <iostream>
#include <cstdlib>
using namespace std;
//在windows编程中DWORD 就是unsigned long
//WINAPI 就是 __stdcall
//LPVOID 就是 void *
//另外 HANDLE 也是 void *
unsigned long __stdcall threadfn(void *);
int main(int argc,char *argv[])
{
void * hthread;
unsigned long threadid;
int i;
for(i =0; i<10;i++)
{
//创建一个线程,threadfn是线程的函数的地址
hthread = CreateThread(NULL,0,threadfn,&i,0,&threadid);
if(hthread)
{
cout << "线程" << i << "已经启动" <<endl;
//关闭一个线程
CloseHandle(hthread);
}
}
Sleep(2000);//主线程挂起一段时间
return 0;
}
unsigned long __stdcall threadfn(void *k)
{
int n = (*(int *)k);
while(true)
{
cout<<n<<endl;
}
return 0;
}
/**********************
taskques.cpp
线程的等待
主线程维持一个线程的循环,当一个子线程结束是立即启动另一个子线程
**********************/
#include <windows.h>
#include <iostream>
#include <cstdlib>
#define NUM 2
using namespace std;
DWORD __stdcall threadfn(LPVOID k);
/*
等待一个线程
int main(int argc,char *argv[])
{
HANDLE hth[NUM];
DWORD thid;
int i = 0;
hth[i] = CreateThread(NULL,0,threadfn,&i,0,&thid);
while(true)
{
WaitForSingleObject(hth[i],INFINITE);//等待一个线程结束
CloseHandle(hth[i]);
i ++;
i %= 2;
hth[i] = CreateThread(NULL,0,threadfn,&i,0,&thid);//一个线程结束后,马上创建另一个线程
}
CloseHandle(hth[0]);
CloseHandle(hth[1]);
Sleep(2000);
return 0;
}
*/
/**********************
等待多个线程,维持一个循环队列
**********************/
int main(int argc,char *argv[])
{
HANDLE hth[NUM];
DWORD thid[NUM];
int i;
int index;
DWORD rc;
//初始化所有线程
for(i=0;i<NUM;i++)
{
hth[i] = CreateThread(NULL,0,threadfn,(LPVOID)i,0,thid+i);
}
//当一个线程结束时启动另一个线程
while(true)
{
rc = WaitForMultipleObjects(NUM,hth,false,INFINITE);
index = rc - WAIT_OBJECT_0;
//CloseHandle(hth[index]);
i++;
hth[index] = CreateThread(NULL,0,threadfn,(LPVOID)i,0,thid+index);
}
//关闭所有线程
for(i=0;i<NUM;i++)
{
CloseHandle(hth[i]);
}
Sleep(2000);
return 0;
}
/**********************
子线程
**********************/
DWORD __stdcall threadfn(LPVOID k)
{
cout<<"线程"<<(int)k<<"正在启动..."<<endl;
srand(GetTickCount() );
Sleep(rand()%8 * 500 + 500);
cout<<"线程"<<(int)k<<"正在退出..."<<endl;
return ((DWORD)k);
}