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

290 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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/

0
On

Instead of MinGW you should use MinGW-w64, which is much more maintained and up to date and supports both Windows 32-bit and 64-bit.

As for threading, any MinGW(-w64) will provide the Windows threads API, but any MinGW-w64 build with POSIX threads support (like the standalone builds from https://winlibs.com/) will also allow you to use pthreads on Windows.

If for some reason you are stuck with classic MinGW you could also take a look at https://sourceforge.net/projects/pthreads4w/ to still be able to use pthreads.