#include<stdio.h>
#include<Windows.h>
enum {THREAD_MAX=40,THREAD_MAX_LIVE=20};
typedef struct _THERAD_PARAM_{
void *p1, *p2,*p3;
int i1, i2, i3;
HANDLE h1, h2,h3;
}THREAD_PARAM,*PTHREAD_PARAM;
DWORD WINAPI
ThreadWorker(PVOID pArg){
HANDLE hSemaphore;
BOOL *pbStopMessage;
PTHREAD_PARAM pThreadArg = (PTHREAD_PARAM)pArg;
///////////// 解析线程参数 ///////////////////
pbStopMessage = (BOOL*)pThreadArg->p1;
hSemaphore =pThreadArg->h1;
///////////// 死循环直到 bStopMessage = true ////////
while(!*pbStopMessage){
DWORD dwRet = WaitForSingleObject(hSemaphore,100);
if (dwRet != WAIT_OBJECT_0) continue;
// Do you work here
// net use
// wmic
// net del
printf("threadId:%d\n",GetCurrentThreadId());
getchar();
ReleaseSemaphore(hSemaphore, 1, NULL);
}
delete pArg;
return 0;
}
int main()
{
HANDLE arrhThread[THREAD_MAX];
LPSTR arrIPs[40];
HANDLE hSemaphore;
BOOL bStopMessage= false;
///////////////// 准备线程参数 /////////////////
hSemaphore = CreateSemaphore( NULL, THREAD_MAX_LIVE, THREAD_MAX_LIVE, NULL);
/*
THREAD_PARAM thread_arg;
thread_arg.h1 = hSemaphore;
thread_arg.p1 = &bStopMessage;
*/
///////////////// 创建线程 /////////////////////
for (int i=0; i<THREAD_MAX; i++){
PTHREAD_PARAM pArg = new THREAD_PARAM;
pArg->h1 = hSemaphore;
pArg->p1 = &bStopMessage;
pArg->p2 = arrIPs+i;
arrhThread[i] = CreateThread(NULL, 0, ThreadWorker,pArg, 0,NULL);
}
//////////////// 等待线程结束 //////////////////
Sleep(60*10*1000);
/////////////// 结束所有线程 //////////////////
bStopMessage = true;
MsgWaitForMultipleObjects(THREAD_MAX,arrhThread,true,INFINITE,0);
CloseHandle(hSemaphore);
return 0;
}
多线程代码编写学习
最新推荐文章于 2022-07-24 19:13:37 发布