返回狼盟编程首页
编程搜索 [狼盟旧档]
论坛统计


请输入搜索关键字:
├─◆ 狼盟首页 > 查看贴子 > 详细信息

楼主

用C++能写控制台下的多线程程序吗,怎么写啊


请给点建议,或推荐本书看看,谢谢。





GCC [ 1 楼 ]
2006-04-19 19:26:00
当然可以依赖于你的操作系统和编译器 

abc8401 [ 2 楼 ]
2006-04-19 19:31:00
我用的是WindowsXP SP2 + VC6.0,VS2005,请具体指点一下,谢谢。 

GCC [ 3 楼 ]
2006-04-19 20:54:00
那就很容易了使用容易 深入难MSDN 里提供的例子#include <windows.h>#include <strsafe.h>#define MAX_THREADS 3#define BUF_SIZE 255typedef struct _MyData {    int val1;    int val2;} MYDATA, *PMYDATA;DWORD WINAPI ThreadProc( LPVOID lpParam ) {     HANDLE hStdout;    PMYDATA pData;    TCHAR msgBuf[BUF_SIZE];    size_t cchStringSize;    DWORD dwChars;    hStdout = GetStdHandle(STD_OUTPUT_HANDLE);    if( hStdout == INVALID_HANDLE_VALUE )        return 1;    // Cast the parameter to the correct data type.    pData = (PMYDATA)lpParam;    // Print the parameter values using thread-safe functions.    StringCchPrintf(msgBuf, BUF_SIZE, TEXT("Parameters = %d, %d "),         pData->val1, pData->val2);     StringCchLength(msgBuf, BUF_SIZE, &cchStringSize);    WriteConsole(hStdout, msgBuf, cchStringSize, &dwChars, NULL);    // Free the memory allocated by the caller for the thread     // data structure.    HeapFree(GetProcessHeap(), 0, pData);    return 0; }  void main(){    PMYDATA pData;    DWORD dwThreadId[MAX_THREADS];    HANDLE hThread[MAX_THREADS];     int i;    // Create MAX_THREADS worker threads.    for( i=0; i<MAX_THREADS; i++ )    {        // Allocate memory for thread data.        pData = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,                sizeof(MYDATA));        if( pData == NULL )            ExitProcess(2);        // Generate unique data for each thread.        pData->val1 = i;        pData->val2 = i+100;        hThread[i] = CreateThread(             NULL,              // default security attributes            0,                 // use default stack size              ThreadProc,        // thread function             pData,             // argument to thread function             0,                 // use default creation flags             &dwThreadId[i]);   // returns the thread identifier          // Check the return value for success.          if (hThread[i] == NULL)         {            ExitProcess(i);        }    }    // Wait until all threads have terminated.    WaitForMultipleObjects(MAX_THREADS, hThread, TRUE, INFINITE);    // Close all thread handles upon completion.    for(i=0; i<MAX_THREADS; i++)    {        CloseHandle(hThread[i]);    }}