采用队列处理消息大概是很多核心代码都会选择的方式,时间是天然的优先级,采用优先队列也无妨,主要是要采用临界区,这样的代码效率可能低一点,但是比起不用要健壮一些。 #include <list> #include <iostream> #include <windows.h> using namespace std; list<int> a; // 队列 CRITICAL_SECTION cs; // 临界区 #define WRITE_THREAD 3 #define READ_THREAD 2 DWORD __stdcall write_list(LPVOID lpParam) { int w = 1000; while(true){ EnterCriticalSection(&cs); // 进入临界区 if(a.size() < 500){ // 容器容量控制在500个 a.push_back(w); } else { LeaveCriticalSection(&cs); // 容器容量达到上限,离开临界区,w不加,下一次放入 continue; } LeaveCriticalSection(&cs); // 离开临界区 w++; if(w >= 10000) w = 1000; } } DWORD __stdcall read_list(LPVOID lpParam) { while(true){ EnterCriticalSection(&cs); // 进入临界区 if(a.size() != 0){ cout << a.front() << " size " << a.size() <<endl; a.erase(a.begin()); } LeaveCriticalSection(&cs); // 离开临界区 } } int main() { InitializeCriticalSection(&cs); // 初始化临界区 HANDLE write_thread[ WRITE_THREAD ]; HANDLE read_thread[ READ_THREAD ]; for(int i = 0; i < WRITE_THREAD; i++){ write_thread[i] = CreateThread(NULL, 0, write_list, NULL, 0, 0); // 开启写线程 } for(int i = 0; i < READ_THREAD; i++){ read_thread[i] = CreateThread(NULL, 0, read_list, NULL, 0, 0); // 开启读线程 } system("Pause"); for(int i = 0; i < WRITE_THREAD; i++){ CloseHandle(write_thread[i]); } for(int i = 0; i < READ_THREAD; i++){ CloseHandle(read_thread[i]); } DeleteCriticalSection(&cs); return 0; }