30个线程,300个任务要执行,同时每个线程只能执行一个任务,如何做
30个线程,300个任务要执行,同时每个线程只能执行一个任务,怎么做?
queue<int> m_queueThread;//任务列表
如题:30个线程,300个任务要执行,同时每个线程只能执行一个任务
全部执行完后等待5秒后全部任务重新开始,直到用户发送命令终止
我这么写有错误,还有什么好的方法?
------解决方案--------------------
你是出了什么问题了?
------解决方案--------------------
是设计问题?还是你的代码有什么问题,说具体一点
------解决方案--------------------
queue<int> m_queueThread;//任务列表
- C/C++ code
//30个线程,300个任务要执行,同时每个线程只能执行一个任务 //全部执行完后等待5秒后全部任务重新开始,直到用户发送命令终止 #include <windows.h> #include <vector> #include <queue> using namespace std; HANDLE hSemaphore; const int NUM_TASK=300;//总任务数 const int NUM_THREAD=30;//开启线程数n个 const int NUM_WAIT=5*1000;//任务全部结束后隔n秒后,重新开始 static bool b_stop=true; CRITICAL_SECTION m_cs; HANDLE hEvent; static int si_thr;//任务序号 /************************ *线程 * *************************/ unsigned long __stdcall ThreadFunc(void* lpParam) { queue<int>* q_Thred=(queue<int>*)lpParam; while(b_stop) { EnterCriticalSection(&m_cs); if(q_Thred->empty())//队列为空,任务全部完成 { printf("开始等待\n"); printf("正在等待...\n"); DWORD dwWaritRes=WaitForSingleObject(hEvent,NUM_WAIT); switch(dwWaritRes) { case WAIT_OBJECT_0: printf("遇到事件结束等待\n"); //break; case WAIT_TIMEOUT: printf("等待结束!\n"); b_stop=0; break; break; } } int i_newNum=q_Thred->front(); q_Thred->pop();//取出队列,已完成该任务 LeaveCriticalSection(&m_cs); DWORD dwWaitResult; dwWaitResult = WaitForSingleObject( hSemaphore, // handle to semaphore INFINITE); // zero-second time-out interval switch (dwWaitResult) { // The semaphore object was signaled. case WAIT_OBJECT_0: printf("%3d:正在执行任务%3d\n",si_thr++,i_newNum);//(*q_Thred).front()); break; // Semaphore was nonsignaled, so a time-out occurred. case WAIT_TIMEOUT: printf("%3d:TIMEOUT!!!!!!!!!!!!!!!!!!!!",si_thr++); break; } if (!ReleaseSemaphore( hSemaphore, // handle to semaphore 1, // increase count by one NULL) ) // not interested in previous count { printf("ReleaseSemaphore error: %d\n", GetLastError()); } } return 0; } bool Start(void) { hSemaphore = CreateSemaphore( NULL, // default security attributes NUM_THREAD, // initial count NUM_THREAD, // maximum count NULL); // unnamed semaphore if (hSemaphore == NULL) { printf("CreateSemaphore error: %d\n", GetLastError()); } //std::vector<int> m_queueThread;// queue<int> m_queueThread;//任务列表 for(int i=1;i<=NUM_TASK;i++) { m_queueThread.push(i); } DWORD ThreadID; for(int i=0;i<NUM_THREAD;i++) { HANDLE handle=CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadFunc, &m_queueThread, 0, &ThreadID); SetThreadPriority(handle,THREAD_PRIORITY_IDLE); } return true; } int main() { int nRetCode = 0; InitializeCriticalSection(&m_cs); hEvent=CreateEvent(NULL,TRUE,FALSE,NULL); si_thr=0; if(Start()) printf("结束!\n"); { // SetEvent(hEvent); } //DeleteCriticalSection(&m_cs); return nRetCode; }
如题:30个线程,300个任务要执行,同时每个线程只能执行一个任务
全部执行完后等待5秒后全部任务重新开始,直到用户发送命令终止
我这么写有错误,还有什么好的方法?
------解决方案--------------------
你是出了什么问题了?
------解决方案--------------------
是设计问题?还是你的代码有什么问题,说具体一点
------解决方案--------------------