我关注this tutorial。我可以通过命令行编译example:
g++ -std=gnu++0x AtomicCounter.cpp -o AtomicCounter -lpthread
它工作正常,但是当我运行时
./AtomicCounter
它给出错误:
在抛出' std :: system_error'的实例后终止调用 what():启用多线程以使用std :: thread:不允许操作 中止(核心倾销)
我发布了AtomicCounter.cpp
#include <thread>
#include <atomic>
#include <iostream>
#include <vector>
struct AtomicCounter {
std::atomic<int> value;
AtomicCounter() : value(0) {}
void increment(){
++value;
}
void decrement(){
--value;
}
int get(){
return value.load();
}
};
int main(){
AtomicCounter counter;
std::vector<std::thread> threads;
for(int i = 0; i < 10; ++i){
threads.push_back(std::thread([&counter](){
for(int i = 0; i < 500; ++i){
counter.increment();
}
}));
}
for(auto& thread : threads){
thread.join();
}
std::cout << counter.get() << std::endl;
return 0;
}
编辑:
感谢@Kerrek SB,当我改为pthread
而不是lpthread
时,它会有效。
但我不明白为什么。有人可以帮我解释一下吗?
有关更多信息,我运行了strace ./AtomicCounter
access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory)
open("/lib/i386-linux-gnu/libpthread.so.0", O_RDONLY|O_CLOEXEC) = 3
read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\320]\0\0004\0\0\0"..., 512) = 512
fstat64(3, {st_mode=S_IFREG|0755, st_size=134614, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7685000
mmap2(NULL, 111276, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0xb7669000
mmap2(0xb7681000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x18000) = 0xb7681000
mmap2(0xb7683000, 4780, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0xb7683000
close(3)
= 0