MinGW and std::thread

2019-01-19 12:23发布

So I've been trying to get the following code to compile and run on Windows by using a MinGW compiler.

#include <iostream>
#include <thread>

void test()
{
    std::cout << "test" << std::endl;
}

int main()
{
    std::thread t(test);
}

I'm compiling with the following command:

g++ -std=c++11 test.cpp -o test.exe

Now the problem is the version of MinGW one should use and I've tried about all the versions I know of.

  1. MinGW-builds: thread-win32
  2. MinGW-builds: thread-posix
  3. MinGW-w64: stdthread experimental rubenvb
  4. MinGW-w64: stdthread experimental rubenvb 4.7

Number 1 doesn't work, since GCC apparently only supports pthread stuff internally.

Number 2 does compile and it essentially even outputs test (see the last line of the output), but it also crashes with the error:

terminate called without an active exception

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
test

Number 3 and 4 again do compile, but they don't output test and instead instantly crashes, but with a more descriptive output:

terminate called after throwing an instance of 'std::system_error'
  what():  Enable multithreading to use std::thread: Operation not permitted

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

Google brought me of course to the GCC bug tracker and some other posts, that suggested to use -pthread, which doesn't help at all.

I've also tried manually linking against winpthread and pthread, but that doesn't do anything either.

There's also no difference between -std=c++11 and -std=gnu++11...

I'm really lost right now and don't know, if it's at all possible to get a MinGW version, that supports std::thread, but maybe I'm just overlooking some compiler flags. I hope someone out there can help me!

2条回答
甜甜的少女心
2楼-- · 2019-01-19 13:02

You forgot to join your thread:

t.join();
查看更多
Summer. ? 凉城
3楼-- · 2019-01-19 13:13

FYI, there is already a native win32 implementation of std::thread and sync primitives. It is a header-only library and works on any C++11 compliant version of MinGW. https://github.com/meganz/mingw-std-threads

查看更多
登录 后发表回答