c++ - CreateThread 似乎表现得像 fork()

标签 c++ visual-studio-2010 fork createthread

我有这个功能

int APIENTRY _tWinMain(HINSTANCE hInstance,
                 HINSTANCE hPrevInstance,
                 LPTSTR    lpCmdLine,
                 int       nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);

// TODO: Place code here.
MSG     msg;
HACCEL  hAccelTable;
int     i;
DWORD   dwThreadIdArray[NUM_THREADS]; //edited after first post
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
PARAM_PASSED *paramPassed = NULL;
std::ostringstream ss;
std::wstring str;

// Initialize global strings
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_LSP3, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);

// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
    return FALSE;
}

hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_LSP3));

// Initialize GDI+ 
GdiplusStartup( &gdiplusToken, &gdiplusStartupInput, NULL); 

// Create event in order to let the other threads know
// when they can start posting message
hStartEvent = CreateEvent(  NULL,                   // default security attributes
                            TRUE,                   // manual-reset event
                            FALSE,                  // initial state is nonsignaled
                            TEXT("StartEvent"));    // object name

if(hStartEvent == NULL)
{
    ss << "_tWinMain: CreateEvent failed" << std::endl;
    str = string2wideString(ss.str().c_str()); 
    OutputDebugString(str.c_str());
    return 1;
}

// Create threads
for(i = 0; i < NUM_THREADS; i++)
{
    paramPassed = NULL;
    threadHandles[i] = CreateThread(NULL,                   // security context is default 
                                    0,                      // stack size is default
                                    rectAnalyzer,           // start routine is rectAnalyzer
                                    paramPassed,            // parameter pointer is paramPassed 
                                    0,                      // thread active
                                    &dwThreadIdArray[i]);   // variable used to store thread id
    if(threadHandles[i] == NULL)
    {
        ss << "_tWinMain: error CreateThread " << i << std::endl;
        str = string2wideString(ss.str().c_str()); 
        OutputDebugString(str.c_str());
    }
    else
    {
        ss << "_tWinMain: created thread " << i << std::endl;
        str = string2wideString(ss.str().c_str()); 
        OutputDebugString(str.c_str());
    }
}

// Let other threads start
SetEvent(hStartEvent);

// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
    if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

// Wait for all threads
WaitForMultipleObjects(NUM_THREADS, threadHandles, TRUE, INFINITE);

for(i = 0; i < NUM_THREADS; i++)
{
    CloseHandle(threadHandles[i]);
}

//Releases GDI+
Gdiplus::GdiplusShutdown(gdiplusToken);

return (int) msg.wParam;
}

我得到了这个输出:

_tWinMain: created thread 0
_tWinMain: created thread 0
_tWinMain: created thread 1
_tWinMain: created thread 0
_tWinMain: created thread 1
_tWinMain: created thread 2  
_tWinMain: created thread 0
_tWinMain: created thread 1
_tWinMain: created thread 2
_tWinMain: created thread 3
The thread 'Win32 Thread' (0x159c) has exited with code 0 (0x0).
The thread 'Win32 Thread' (0x12bc) has exited with code 0 (0x0).
The thread 'Win32 Thread' (0x102c) has exited with code 0 (0x0).
The thread 'Win32 Thread' (0x1594) has exited with code 0 (0x0).
The thread 'Win32 Thread' (0x107c) has exited with code 1 (0x1).
The program '[2308] lsp3.exe: Native' has exited with code 0 (0x0).

为什么我得到线程 0...2 的多个输出?我不知道我是在创建 4 个线程还是 10 个线程。而且最后我似乎创建了 4 个线程加上主线程。

最佳答案

您没有在循环中清除字符串流 ss,因此输出只是累积:

thread 0
thread 0 1
thread 0 1 2
thread 0 1 2 3

在每次输出后添加一个ss.str("")

关于c++ - CreateThread 似乎表现得像 fork(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6213045/

相关文章:

C++如何将参数绑定(bind)到具有相同返回类型的函数并将它们全部存储在一个容器中

c++ - 为什么这个 AVX 内部函数会导致 "Segmentation fault"有 clang,而不是 GCC?

visual-studio-2010 - 每次构建前清除 "Error List"警告的 Visual Studio 2010 插件/代码

c - Telnet session ,fork 与 thread

c - C程序中的fork()

c++ - CMake 在创建简单项目时无法在 Windows 中找到 SFML 目录

c++ - gcc3 和 gcc4 关于未初始化变量的区别

xml - 在 Visual Studio 中使用 XSL 标记或拆分字符串

entity-framework - EF 4 中 "include foreign key columns in the model"选项的优缺点是什么

python - 动态命名进程