`
vyloy
  • 浏览: 78614 次
  • 性别: Icon_minigender_1
  • 来自: 佛山
社区版块
存档分类
最新评论

c++11 多线程

    博客分类:
  • C++
阅读更多
#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;
}


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

引用

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


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

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

引用

error: ‘sleep_for’ is not a member of ‘std::this_thread’


通过增加-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


作者:翁志艺
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics