代码:
//main.cpp
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
std::mutex g_lock;
void func()
{
std::lock_guard<std::mutex> locker(g_lock);
std::cout << "entered thread" << std::this_thread::get_id() << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "leaving thread" << std::this_thread::get_id() << std::endl;
}
int main()
{
std::thread t1(func);
std::thread t2(func);
std::thread t3(func);
t1.join();
t2.join();
t3.join();
return 0;
}
我在Linux上编译上面代码时出现了以下错误:
terminate called after throwing an instance of ‘std::system_error’
what(): Enable multithreading to use std::thread: Operation not permitted
Aborted (core dumped)
解决方案:
g++ -Wall -fexceptions -std=c++11 -g -pthread -Wl,–no-as-needed -std=c++11 main.cpp -o main
注意:
-Wl,–no-as-needed 这中间不能出现空格,如果出现空格,编译会出现错误
参考资料:
https://stackoverflow.com/questions/23677690/compiling-multithread-code-with-codeblocks-gnu-compiler