トップページへ

C++で「Enable multithreading to use std::thread: Operation not permitted」というエラーになる場合の対処

小粋空間 » Programming Language » C/C++ » C++で「Enable multithreading to use std::thread: Operation not permitted」というエラーになる場合の対処

C++で「Enable multithreading to use std::thread: Operation not permitted」というエラーになる場合の対処について紹介します。

1.問題点

C++11で実装されたstd::threadを使ったプログラムを作ってみました。

sample.cpp

#include <cstdlib>
#include <iostream>
#include <thread>
 
void task(const std::string msg) {
    std::cout << msg << std::endl;
}
 
int main(int argc, char **argv) {
    std::thread t(task, "Hello World!!");
    t.join();
    return 0;
}

が、このプログラムを実行すると下記の「Enable multithreading to use std::thread: Operation not permitted」というエラーが発生します。

% g++ -std=c++11 sample.cpp
% ./a.out
terminate called after throwing an instance of 'std::system_error'
  what():  Enable multithreading to use std::thread: Operation not permitted
中止 (コアダンプ)

が、このエラーが発生する理由がわかりません。

ということで、このエラーになる場合の対処について紹介します。

2.原因と対処

原因は、コンパイル時に"-pthread"オプションを付与していないためです。

std::threadを利用したプログラムで"-pthread"オプションなしでコンパイルすると、コンパイル時にはエラーにならずに実行時エラーになります。

ということで、"-pthread"オプションを付与してコンパイルすればOKです。

% g++ -std=c++11 -pthread sample.cpp
% ./a.out
Hello World!!

3.参考サイト

参考サイトは下記です。ありがとうございました。

« 前の記事へ

次の記事へ »

トップページへ