I am following this tutorial. I can compile the example by command line:
g++ -std=gnu++0x AtomicCounter.cpp -o AtomicCounter -lpthread
It works fine but when I run
./AtomicCounter
It gives the error:
terminate called after throwing an instance of 'std::system_error' what(): Enable multithreading to use std::thread: Operation not permitted Aborted (core dumped)
I posted the code of 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;
}
EDIT:
Thank @Kerrek SB, it works when I changed to pthread
instead of lpthread
.
But I don't understand why. Can someone explain for me?
For more informations, I ran 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