问题描述
所以我一直在尝试使用 MinGW 编译器让以下代码在 Windows 上编译和运行。
#include <iostream>
#include <thread>
#include <future>
void ThreadWork(std::promise<int> &&p)
{
// Pre-return from thread,do work after returning a value
/* if else and things */ p.set_value(0);
std::cout << "From thread" << std::endl;
// More work
}
int main()
{
std::promise<int> p;
std::future<int> f = p.get_future();
std::thread th(ThreadWork,std::move(p));
// Get return value from thread
int ret = f.get();
}
上面给出了错误:
error: aggregate 'std::promise<int> p' has incomplete type and cannot be defined
75 | std::promise<int> p;
error: variable 'std::future<int> f' has initializer but incomplete type
76 | std::future<int> f = p.get_future();
error: 'thread' is not a member of 'std'
77 | std::thread th(readInThread,callback,std::move(p));
尝试使用官方的 MinGW 构建,尝试使用 meganz/mingw-std-threads(即使它设置为 0x0A00,似乎也没有设置 _WIN32_WININT
之类的错误,如果我尝试手动设置它,编译失败并重新声明),还有更多,一无所获...
我也尝试与 pthreads 链接:-lpthread
不走运 :(
为什么 C++11 标准特性仍未在 MinGW 中实现?他们目前的替代方案是什么?
解决方法
future
和 promise
在 MinGW-w64 中已经工作了很长时间。我不满足于官方的二进制发行版。因此,我使用 https://github.com/niXman/mingw-builds 自行构建 MinGW-w64。
使用类 Unix 控制台 (MSYS2) 克隆存储库后的步骤如下:
cd /c/mingw-builds/
mkdir BuildRoot
git pull origin develop
git checkout develop
cd BuildRoot
../build --mode=gcc-10.2.0 --arch=x86_64 --buildroot=/c/mingw-builds/BuildRoot --update-sources --exceptions=seh --threads=posix --enable-languages=c++ --jobs=48 --rt-version=v7
#(https://stackoverflow.com/questions/32221221/mingw-x64-windows-plugin-needed-to-handle-lto-object)
mkdir mingw64/lib/bfd-plugins
cp mingw64/libexec/gcc/x86_64-w64-mingw32/10.2.0/liblto_plugin-0.dll mingw64/lib/bfd-plugins/liblto_plugin-0.dll
然后使用编译器,它应该像魅力一样工作并支持 future
和 promise
。