Search code examples
c++cmultithreadingcpumulticore

How to use source-level multithreading in C/C++?


I need to gain performance by using 2 hardware CPUs on MS Windows. I write the following code:

#include "windows.h"

int main1(int argc, CHAR* argv[])
{
    // ...
}

int main2(int argc, CHAR* argv[])
{
    // ...
}

to write two main functions - one for every CPU. The compiler tells me:

D:/MinGW/x86_64-w64-mingw32/lib/../lib/libmingw32.a(lib64_libmingw32_a-crt0_c.o):crt0_c.c:(.text+0x3d): undefined reference to `WinMain'
collect2.exe: error: ld returned 1 exit status

What am i doing wrong? How can i write two mains to make them run on two different CPUs? _tmain1, _tmain2 does not help either.


Solution

  • You create one main, and start another thread for which you set the processor affinity.

    pseudocode:

    int main1(){...}
    int main2(){...}
    
    int main()
    {
      main2_thread = StartThreed( main2 );
      SetProcessorAffinity( this_thread, 0 );
      SetProcessorAffinity( main2_thread, 1 );
      main1();
    }