1

下面的代码会编译并运行,只是输出不是我所期望的。我希望程序创建 n 个线程(取决于可用的多核数量)并运行一个在程序末尾找到的简单例程用于输出

“测试:”

后跟数字 1-10。相反,我得到的是一个输出,它确实写了一些数字,但最多不超过两个,并且函数 threadmain 似乎没有完全在一个线程上运行,但它在某种程度上输出 testing: 012 在其他线程上。我知道多线程会破坏输出,但我应该在屏幕上的某处看到数字 3、4、5、6、7、8、9,但它没有出现。

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <cmath>
#include <iostream>

HANDLE *m_threads = NULL;
static DWORD_PTR WINAPI threadMain(void* p);

DWORD_PTR GetNumCPUs()
{
  SYSTEM_INFO m_si = {0, };
  GetSystemInfo(&m_si);
  return (DWORD_PTR)m_si.dwNumberOfProcessors;
}

CRITICAL_SECTION g_crit_sec;
static int g_start = 0;

int main(int argc, char **args)
{
  DWORD_PTR c = GetNumCPUs();

  m_threads = new HANDLE[c];

  InitializeCriticalSectionAndSpinCount(&g_crit_sec, 0x80000400);

  for(DWORD_PTR i = 0; i < c; i++)
  {
    DWORD_PTR m_id = 0;
    DWORD_PTR m_mask = 1 << i;

    m_threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadMain, (LPVOID)i, NULL, &m_id);
    SetThreadAffinityMask(m_threads[i], m_mask);

    //wprintf(L"Creating Thread %d (0x%08x) Assigning to CPU 0x%08x\r\n", i, (LONG_PTR)m_threads[i], m_mask);
  }

  return 0;
}
static DWORD_PTR WINAPI threadMain(void* p)
{
    double result = 0.0;

    for (int i = 0; i < 10; i++)
    {
        std::cout<<"testing: "<<i<<std::endl;
        //result = result + sin(i) * tan(i);
    }

  return 0;
}
4

1 回答 1

5

您的应用程序在您的线程完成运行之前终止。启动线程后,在主函数中调用或更恰当的调用,如下所示Sleep()WaitForMultipleObjects()

int main(int argc, char **args)
{
  DWORD_PTR c = GetNumCPUs();

  m_threads = new HANDLE[c];

  InitializeCriticalSectionAndSpinCount(&g_crit_sec, 0x80000400);

  for(DWORD_PTR i = 0; i < c; i++)
  {
    DWORD_PTR m_id = 0;
    DWORD_PTR m_mask = 1 << i;

    m_threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadMain, (LPVOID)i, NULL, (LPDWORD)&m_id);
    SetThreadAffinityMask(m_threads[i], m_mask);

    //wprintf(L"Creating Thread %d (0x%08x) Assigning to CPU 0x%08x\r\n", i, (LONG_PTR)m_threads[i], m_mask);
  }

  // Waits for all started threads to complete:
  WaitForMultipleObjects(c, m_threads, TRUE, INFINITE);

  return 0;
}
于 2012-11-19T18:25:33.007 回答