Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread doesn't work with an error: Enable multithreading to use std::thread: Operation not permitted

I created and executed a simple thread on my system. when I execute this program, I have the error message : Enable multithreading to use std::thread: Operation not permitted

some details about my system :

  • linux ubuntu 13.10
  • g++ 4.8.1

I compile the source code including the library pthread

The source code:

#include <iostream> #include <thread>   using namespace std;  void func(void) {   cout << "test thread" << endl; }   int main() {   cout << "start" << endl;   thread t1 (func);    t1.join();    cout << "end" << endl;    return 0; } 
like image 844
user2925158 Avatar asked Oct 27 '13 14:10

user2925158


People also ask

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).

What happens if you don't join a thread in C?

If you don't join these threads, you might end up using more resources than there are concurrent tasks, making it harder to measure the load. To be clear, if you don't call join , the thread will complete at some point anyway, it won't leak or anything.

What will happen if passing reference through std :: thread?

If you have used std::thread or std::bind , you probably noticed that even if you pass a reference as parameter, it still creates a copy instead. From cppreference, The arguments to the thread function are moved or copied by value.

Can a thread spawn another thread C++?

A thread does not operate within another thread. They are independent streams of execution within the same process and their coexistence is flat, not hierarchical. Some simple rules to follow when working with multiple threads: Creating threads is expensive, so avoid creating and destroying them rapidly.


1 Answers

It seems that you are trying to use C++11 threads. If it is true, then

  1. correct #include <thread> and #include <iostream>, i.e. do not use " in these lines and add # in front of them.
  2. compile with g++ -std=c++11 q.cpp -lpthread (dependency order matters for newer g++)

Hint: when you are using threads in a static linked library and use this library in an executable, then you have to add the flag -pthread to the link command for the executable. Example:

g++ Obj1.o Obj2.o MyStaticLib.a -o MyExecutable -pthread 
like image 196
Igor Popov Avatar answered Sep 23 '22 09:09

Igor Popov