Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Threads, std::system_error - operation not permitted? [duplicate]

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?

like image 704
FreelanceConsultant Avatar asked Jun 24 '13 11:06

FreelanceConsultant


1 Answers

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
like image 154
billz Avatar answered Nov 18 '22 04:11

billz