Question

The code below does compile and run except that the output is not what I expect it to be. I wanted the program to create n-number of threads (depending on the number of multicores available) and run a simple routine found at the end of the program for outputting

"testing:"

followed by a number 1-10. What I get instead is an output that does write a few numbers but it doesn't go past two at the most and the function threadmain doesn't seem to completely run on one thread but it somewhat outputs testing: 012 in others. I know multithreading will mangle output but I should see the numerals 3,4,5,6,7,8,9 somewhere on the screen but it doesn't show up.

#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;
}
Was it helpful?

Solution

Your application is terminating before your threads are done running. Put a Sleep() or more appropriately a WaitForMultipleObjects() call in your main function after starting the threads, like this:

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top