我尝试使用 g++ 4.7 使用 C++11 主题库。首先我有一个问题:预计下一个版本不需要手动链接 pthread 库吗?
所以我的程序是:
#include <iostream>
#include <vector>
#include <thread>
void f(int i) {
std::cout<<"Hello world from : "<<i<<std::endl;
}
int main() {
const int n = 4;
std::vector<std::thread> t;
for (int i = 0; i < n; ++i) {
t.push_back(std::thread(f, i));
}
for (int i = 0; i < n; ++i) {
t[i].join();
}
return 0;
}
我编译:
g++-4.7 -Wall -Wextra -Winline -std=c++0x -pthread -O3 helloworld.cpp -o helloworld
它返回:
Hello world from : Hello world from : Hello world from : 32
2
pure virtual method called
terminate called without an active exception
Erreur de segmentation (core dumped)
问题是什么以及如何解决?
更新:
现在使用互斥锁:
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
static std::mutex m;
void f(int i) {
m.lock();
std::cout<<"Hello world from : "<<i<<std::endl;
m.unlock();
}
int main() {
const int n = 4;
std::vector<std::thread> t;
for (int i = 0; i < n; ++i) {
t.push_back(std::thread(f, i));
}
for (int i = 0; i < n; ++i) {
t[i].join();
}
return 0;
}
它返回:
pure virtual method called
Hello world from : 2
terminate called without an active exception
Abandon (core dumped)
更新2:嗯......它适用于我的默认GCC(g ++ 4.6),但它与我手动编译的gcc版本(g ++ 4.7.1)一起失败。有没有我忘记编译 g++ 4.7.1 的选项?