问题描述
在MinGW环境下编译多线程程序一定要使用pthread库吗? 我看到头文件在 TrueStudio 中的集成 MinGW 中声明了 _ beginthreadex 函数。但程序运行出现异常。不知道有没有用过_beginthreadex函数。
//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 (__stdcall *) (void *),void *,unsigned *);
_CRTIMP __cdecl __MINGW_NOTHROW void _endthreadex (unsigned);
#endif
更新: 以上信息是不是说明_beginthreadex函数需要MSVC编译器支持,_beginthread函数不支持?
解决方法
不,不必使用 pthreads
。您可以直接使用 Win32 API。
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
如果您担心便携性,您也可以通过 libuv
。
https://docs.microsoft.com/en-us/windows/win32/procthread/creating-threads
,您应该使用 MinGW-w64 而不是 MinGW,它的维护和更新要好得多,并且支持 Windows 32 位和 64 位。
至于线程,任何 MinGW(-w64) 都将提供 Windows 线程 API,但任何支持 POSIX 线程的 MinGW-w64 构建(如 https://winlibs.com/ 的独立构建)也将允许您在窗户。
如果由于某种原因您坚持使用经典 MinGW,您还可以查看 https://sourceforge.net/projects/pthreads4w/ 以仍然能够使用 pthreads。