Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the correct link options to use std::thread in GCC under linux?

Hi I am trying to use std::thread with G++. Here is my test code

#include <thread> #include <iostream>  int main(int, char **){     std::thread tt([](){ std::cout<<"Thread!"<<std::endl; });     tt.join(); } 

It compiles, but when I try to run it the result is:

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

My compiler version:

$ g++ --version g++ (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1 Copyright (C) 2011 Free Software Foundation, Inc. This is free software; see the source for copying conditions.  There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 

What is wrong with my test code?

UPDATE: I use the following command line to compile and run my code.

$ g++ -std=c++0x test.cpp $ ./a.out 

and I tried

$ g++ -std=c++0x -lpthread test.cpp $ ./a.out 

still the same.

like image 587
Earth Engine Avatar asked Dec 27 '11 22:12

Earth Engine


People also ask

Does std :: thread use pthreads?

The std::thread library is implemented on top of pthreads in an environment supporting pthreads (for example: libstdc++).

What does std :: thread do?

std::thread Threads allow multiple functions to execute concurrently. std::thread objects may also be in the state that does not represent any thread (after default construction, move from, detach, or join), and a thread of execution may not be associated with any thread objects (after detach).

Is std :: thread copyable?

std::thread::operator= thread objects cannot be copied (2).

Is GCC multithreaded?

GCC uses a single instance of rtl_data class, representing the current function being compiled in RTL. So far, this should not be a problem as RTL expansion and optimization phase is still single-threaded.


2 Answers

I think on Linux pthread is used to implement std::thread so you need to specify the -pthread compiler option.

As this is a linking option, this compiler option need to be AFTER the source files:

$ g++ -std=c++0x test.cpp -pthread 
like image 104
hmjd Avatar answered Oct 22 '22 19:10

hmjd


In addition to using -std=c++0x and -pthread you must not use -static.

like image 43
Bowie Owens Avatar answered Oct 22 '22 19:10

Bowie Owens