命令列程式也可以多線程。網上查了很多文章都是講視窗介面的,這裡我寫個命令列的,架構很簡單,如下:
// VRP.cpp : 定義控制台應用程式的進入點。//#include "stdafx.h"#include "windows.h"#include "VRP.h"DWORD g_dwRipThreadId = 0;DWORD g_dwOspfThreadId = 0;int _tmain(int argc, _TCHAR* argv[]){ _tprintf(_T("Info: VRP is starting...\n")); LPVOID pvRipParameter = NULL;; HANDLE hRip = CreateThread(NULL, 0, RIP_ThreadProc, pvRipParameter, 0, &g_dwRipThreadId); if(NULL == hRip) { _tprintf(_T("ERRO: Rip Thread create failure!\n")); return 0; } _tprintf(_T("INFO: Rip Thread create success!\n")); ///////////////////////////////////////////////////////// LPVOID pvOspfParameter = NULL;; HANDLE hOspf = CreateThread(NULL, 0, OSPF_ThreadProc, pvOspfParameter, 0, &g_dwOspfThreadId); if(NULL == hOspf) { _tprintf(_T("ERRO: Ospf Thread create failure!\n")); return 0; } _tprintf(_T("INFO: Ospf Thread create success!\n")); //////////////////////////////////////////////////////// Sleep(2000); UINT Msg = MY_MSG; int count = 0; TCHAR * wParam = new TCHAR[MAX_INFO_SIZE]; //create dynamic msg LPARAM IParam = NULL; while(true) { Sleep(2000); if(0 == count % 2) { _stprintf(wParam, _T("main -> rip msg_%d"), ++count); // if(false == PostThreadMessage(g_dwRipThreadId, Msg, (WPARAM)wParam, IParam)) { _tprintf(_T("ERRO: PostThreadMessage -> Rip failure!\n")); } } else { _stprintf(wParam, _T("main -> ospf msg_%d"), ++count); // if(false == PostThreadMessage(g_dwOspfThreadId, Msg, (WPARAM)wParam, IParam)) { _tprintf(_T("ERRO: PostThreadMessage -> Ospf failure!\n")); } } //LRESULT SendMessage(HWND hWnd,UINT Msg,WPARAM wParam,LPARAM IParam); } CloseHandle(hRip); CloseHandle(hOspf); getchar(); return 0;}//DWORD WINAPI RIP_ThreadProc (LPVOID lpParam) { // _tprintf(_T("INFO: RIP_Task has been created!\n")); MSG Msg; _TCHAR * pInfo = NULL; PeekMessage(&Msg, NULL, WM_USER, WM_USER, PM_NOREMOVE); //發訊息變量 UINT uiMsg = MY_MSG; int iCount = 0; TCHAR * wParam = new TCHAR[MAX_INFO_SIZE]; //create dynamic msg LPARAM IParam = NULL; while(true) { if(GetMessage(&Msg, NULL, 0, 0)) //get msg from message queue { switch(Msg.message) { case MY_MSG: pInfo = (_TCHAR *)Msg.wParam; _tprintf(_T("RIP: recv %s\n"), pInfo); break; } } _stprintf(wParam, _T("rip -> ospf msg_%d"), ++iCount); // Sleep(2000); if(false == PostThreadMessage(g_dwOspfThreadId, uiMsg, (WPARAM)wParam, IParam)) { _tprintf(_T("ERRO: PostThreadMessage -> Rip failure!\n")); } } // delete pInfo; return 0;}//DWORD WINAPI OSPF_ThreadProc (LPVOID lpParam) { // _tprintf(_T("INFO: OSPF_Task has been created!\n")); MSG Msg; _TCHAR * pInfo = NULL; PeekMessage(&Msg, NULL, WM_USER, WM_USER, PM_NOREMOVE); while(true) { if(GetMessage(&Msg, NULL, 0, 0)) //get msg from message queue { switch(Msg.message) { case MY_MSG: pInfo = (_TCHAR *)Msg.wParam; _tprintf(_T("OSPF: recv %s\n"), pInfo); break; } } } // delete pInfo; return 0;}
#ifndef _VRP_H_#define _VRP_H_#define MY_MSG WM_USER + 100const int MAX_INFO_SIZE = 20;DWORD WINAPI RIP_ThreadProc (LPVOID lpParam);DWORD WINAPI OSPF_ThreadProc (LPVOID lpParam);#endif