CreateNThread.cpp
上传用户:yida6688
上传日期:2022-07-02
资源大小:8k
文件大小:3k
- //////////////////////////////////////////////////////////////////////////
- // 创建N个线程 //
- //////////////////////////////////////////////////////////////////////////
- #include <process.h>
- #include <windows.h>
- #include <math.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <iostream.h>
- DWORD WINAPI myFunc(LPVOID p);
- BOOL runFlag = TRUE;
- void main(int argc, char *argv[])
- {
- unsigned int runTime;
- int n;
- SYSTEMTIME now;
- WORD stopTimeMinute, stopTimeSecond;
- /* if (argc < 2)
- {
- cout << "参数少于2个..." <<endl;
- ExitProcess(0);
- }
- else
- n = atoi(argv[1]);
- if (argc < 3)
- {
- runTime = 150;
- }
- else
- runTime = atoi(argv[2]);
- */
- n = 5;
- runTime = 140;
-
- GetSystemTime(&now);
- printf("CreateNThread: suite starting at system time
- %d:%d:%dn", now.wHour, now.wMinute, now.wSecond);
- stopTimeSecond = (now.wSecond + (WORD)runTime) % 60;
- stopTimeMinute = now.wMinute + (now.wSecond + (WORD)runTime)/60;
- DWORD threadId;
- for(int i = 0; i < n; ++i)
- {
- if(/*!CreateThread(NULL,
- 0,
- myFunc,
- &i,
- 0,
- &threadId)*/
- !_beginthreadex(NULL,
- 0,
- (unsigned int(_stdcall *)(void *))myFunc,
- (void*)&i,
- 0,
- (unsigned *)&threadId))
- {
- printf("Create %d Thread error: %dn", i, GetLastError());
-
- char err[1000];
- FormatMessage(
- FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_IGNORE_INSERTS,
- NULL,
- GetLastError(),
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
- err,
- 1000,
- NULL
- );
- fprintf(stderr, "error: %sn", err);
-
- ExitProcess(0);
- }
- Sleep(100);
- }
- //cycle while children work...
- while (runFlag)
- {
- GetSystemTime(&now);
- if ((now.wMinute >= stopTimeMinute)
- &&
- (now.wSecond >= stopTimeSecond))
- {
- runFlag = FALSE;
- }
- Sleep(1000);
- }
-
- Sleep(5000);
- }
- //////////////////////////////////////////////////////////////////////////
- DWORD WINAPI myFunc(LPVOID threadId)
- {
- int n = *((unsigned int *)threadId)+1;
- /* if (n==2)
- {
- runFlag = FALSE;
- }*/
- printf("This is %d thread, runFlag: %dn", n, int(runFlag));
- double y;
- const double x = 3.14159;
- const double e = 2.7183;
- int i;
- const int napTime = 1000;
- const int busyTime = 4000;
- while(runFlag)
- {
- for (i = 0; i < busyTime; ++i)
- {
- y = pow(x,e);
- }
- Sleep(napTime);
- }
- SYSTEMTIME now;
- GetSystemTime(&now);
- printf("%d Thread exit at time: %d:%d:%d:%dn", n, now.wHour, now.wMinute,now.wSecond,now.wMilliseconds);
- return 0;
- }