Search code examples
multithreadingclassmingwpthreads-win32

must to use pthread library to compile multithreaded programs in MinGW environment?


must to use pthread library to compile multithreaded programs in MinGW environment? I saw that the header file declared the _ beginthreadex function in the integrated MinGW, in TrueStudio. but there was an exception in the operation of the program. I don't know if I used the _ beginthreadex function.

//process.h
/* Thread initiation and termination functions.
 *
 * NOTE: Apparently _endthread() calls CloseHandle() on the handle of the
 * thread, creating a potential for race conditions, if you are not careful.
 * Basically, you MUST ensure that NOTHING attempts to do ANYTHING with the
 * thread handle after the thread calls _endthread(), or returns from the
 * thread function.
 *
 * NOTE: No old names for these functions.  Use the underscore.
 */
_CRTIMP __cdecl __MINGW_NOTHROW
unsigned long _beginthread (void (*)(void *), unsigned, void *);

_CRTIMP __cdecl __MINGW_NOTHROW  void _endthread (void);

#ifdef __MSVCRT__
_CRTIMP __cdecl __MINGW_NOTHROW  unsigned long _beginthreadex
(void *, unsigned, unsigned (__stdcall *) (void *), void *, unsigned, unsigned *);

_CRTIMP __cdecl __MINGW_NOTHROW  void _endthreadex (unsigned);
#endif

update: Does the above information indicate that the _ beginthreadex function needs to be supported by the MSVC compiler, but not the _ beginthread function?


Solution

  • No don't have to use pthreads. You could use Win32 API directly.

            hThreadArray[i] = CreateThread( 
                NULL,                   // default security attributes
                0,                      // use default stack size  
                MyThreadFunction,       // thread function name
                pDataArray[i],          // argument to thread function 
                0,                      // use default creation flags 
                &dwThreadIdArray[i]);   // returns the thread identifier 
    

    And if you are concerned by portability, you could also go through libuv.

    https://learn.microsoft.com/en-us/windows/win32/procthread/creating-threads

    http://libuv.org/