61

Update in 2022

C++ 17 & 20 now have built in support for multithreading in the standard library. I would suggest using these rather than using the Linux specific pthread library.

Original Question

I wrote a program to test threads on 64 bit kubuntu linux, version 13.04. Actually I robbed the code from someone else who was writing a test program.

#include <cstdlib>
#include <iostream>
#include <thread>

void task1(const std::string msg)
{
    std::cout << "task1 says: " << msg << std::endl;
}

int main(int argc, char **argv)
{
    std::thread t1(task1, "Hello");
    t1.join();

    return EXIT_SUCCESS;
}

I compiled using:

g++ -pthread -std=c++11 -c main.cpp
g++ main.o -o main.out

Then ran:

./main.out

As an aside, when I 'ls -l', main.out shows up in in green text like all executables, but also has an asterisk at the end of its name. Why is this?

Back to the problem in hand: When I ran main.out, an error appeared, which said:

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

Anyone any ideas on how to fix this?

1
  • This question should not be marked duplicated. There are other situation where you can get this error message. Not limited to threading linking issue. Commented Aug 31, 2022 at 18:39

1 Answer 1

109

You are not linking pthread properly, try below command(note: order matters)

g++  main.cpp -o main.out -pthread -std=c++11

OR

Do it with two commands

g++ -c main.cpp -pthread -std=c++11         // generate target object file
g++ main.o -o main.out -pthread -std=c++11  // link to target binary
Sign up to request clarification or add additional context in comments.

11 Comments

You can do it with two commands. But you must specify -pthread both when you compile and when you link.
@billz Would you mind elaborate on why the order of -pthread matters?
you need to compile it first before link it. put -pthread int the end of g++ command will allow g++ link it properly after compiled to .o file
thus also reading the comment of David Schwartz -pthread is mainly needed at the linking stage, not neccesary while compiling?
The GCC manual entry for -pthread specifically says "This option sets flags for both the preprocessor and linker." You should use it when compiling as well as linking.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.