Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 Thread not working [duplicate]

My programs looks like below

#include <iostream>
#include <thread>
#include <exception>

void hello()
{
    std::cout << "Hello world!!!!" << std::endl;
}

int main()
{
    std::cout << "In Main\n";
    std::thread t(hello);
    t.join();
    return 0;
}

When I compile it using the following command I get no errors

g++-4.7 -std=c++11 main.cpp

But when I run it I get the following error

In Main
terminate called after throwing an instance of 'std::system_error'
what():  Operation not permitted
Aborted (core dumped)

Could someone help me with where I am going wrong?

like image 658
Alwin Doss Avatar asked Nov 05 '12 07:11

Alwin Doss


3 Answers

When I use C++11 threads with GCC, i use:

g++ -std=c++0x -pthread -g main.cpp

That works for me.

like image 146
Michael McGuire Avatar answered Oct 03 '22 22:10

Michael McGuire


When compiling your code with g++, use the -pthread option.

Below is the answer I find from stackoverflow: In g++ is C++ 11 thread model using pthreads in the background?

like image 21
billz Avatar answered Oct 03 '22 21:10

billz


Everybody already answered that you need the -pthread argument passed to the compiler. Almost for sure it won't change in 4.8 but according to http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52681 the exception will at least have a nice message stating what's wrong.

like image 36
Wojciech Cierpucha Avatar answered Oct 03 '22 21:10

Wojciech Cierpucha