c++11 多线程

版权声明:拓洲网络创始人翁志艺,官网https://www.yiqishare.com https://blog.csdn.net/iteye_7863/article/details/82545040

#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>

std::mutex g_lock;

void func()
{
g_lock.lock();

std::cout << "entered thread " << std::this_thread::get_id() << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(rand() % 10));
std::cout << "leaving thread " << std::this_thread::get_id() << std::endl;

g_lock.unlock();
}

int main()
{
srand((unsigned int)time(0));

std::thread t1(func);
std::thread t2(func);
std::thread t3(func);

t1.join();
t2.join();
t3.join();

return 0;
}


尝试编译运行上面的代码,运行时报下面的错误

[quote]
terminate called after throwing an instance of 'std::system_error'
what(): Operation not permitted
Aborted
[/quote]

通过增加-lpthread编译参数可以解决
from http://stackoverflow.com/questions/8649828/what-is-wrong-with-this-use-of-stdthread

再编译运行,运行时报下面的错误

[quote]
error: ‘sleep_for’ is not a member of ‘std::this_thread’
[/quote]

通过增加-D_GLIBCXX_USE_NANOSLEEP编译参数可以解决
from http://stackoverflow.com/questions/12523122/what-is-glibcxx-use-nanosleep-all-about

最后,整个编译命令如下:
g++ --std=c++0x -D_GLIBCXX_USE_NANOSLEEP -lpthread thread.c


[color=white]作者:翁志艺[/color]

猜你喜欢

转载自blog.csdn.net/iteye_7863/article/details/82545040