c++11 concurrency error

1
2
3
4
5
6
7
#include <future>

int main()
{
    auto f = std::async([](){return 3;});
    return f.get();
}


g++ -g -std=c++11 -lpthread : I compiled with these options

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


What's wrong with this short program?
My g++ version is 4.8
Last edited on
Code was compiled but the execution was not done properly.
Maybe corrupt library?
Does Everybody have the same problem like me? I suspect not.
I found out what's wrong.
But it's really wierd.
if I add
this_thread::sleep_for() function then it works fine.
when I check with ldd, pthread library is included..

1
2
3
4
5
6
7
8
9
10
11
12
#include <future>
#include <iostream>
using namespace std;
void func1() {
	this_thread::sleep_for(chrono::seconds(1));
}

int main()
{
	auto f = async([](){return 3;});
	cout << f.get();
}
Last edited on
Your source file must come before -lpthread on the command line. The order matters.
compiler option was not the problem.
the sleep_for function made linker to correctly link the library. Even though it was not used in
the main.
Its better to use the compiler flag -pthread than the linker flag -lpthread because the linker flag needs to be positioned after the objects that use the library.

So: g++ -std=c++11 -pthread -o progname progname.cpp

Needing to add a phantom function that is never called is a sign that something is not right.
Topic archived. No new replies allowed.