写爬虫的时候发现单线程太慢,研究了一下多线程写法
// testThread.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include "windows.h"
#define MAX_THREADS 3
//子线程函数
DWORD WINAPI ThreadFun(LPVOID pM)
{
printf("n我是子线程:%dn",pM);
printf("子线程的线程ID号为:%dn", GetCurrentThreadId());
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
printf("我是主线程n");
//HANDLE handle = CreateThread(NULL, 0, ThreadFun, NULL, 0, NULL);
//WaitForSingleObject(handle, INFINITE);
HANDLE hThread[MAX_THREADS];
int i;
for(i = 0; i < MAX_THREADS; i++){
hThread[i] = CreateThread(NULL, 0, ThreadFun,(LPVOID *) i, 0, NULL); //创建多线程
}
if(hThread[i]==NULL)
{
ExitProcess(i);//退出进程
}else{
printf("hThread:,%dn",hThread[i]);
}
WaitForMultipleObjects(MAX_THREADS,hThread,TRUE,INFINITE);//主线程等待子线程结束
for(i = 0; i < MAX_THREADS; i++){
CloseHandle(hThread[i]);//关闭线程
}
return 0;
}