#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
作者:翁志艺
分享到:
相关推荐
cocos2d-x 3.0 中使用的 C++ 11 多线程互斥与同步
C++11多线程编程.zip 代码实例 C++11多线程编程future其他成员函数、shared_future、atomic C++11多线程编程std__atomic续谈、std__async深入谈 C++11多线程编程windows临界区、其他各种mutex互斥量 C++11多线程编程...
C++11多并发学习资料,带有目录列表,中文翻译,清晰明了。
本示例主要演示C++11下的多线程运算,可以加速,对于一些高性能的程序,可以参考
C++11多线程demo,包含在Ubuntu下编译C++11的方法,写了两三个C++11多线程的demo,欢迎下载!
流媒体-H264协议-编码-x264学习-C++11多线程实现编码(四) https://blog.csdn.net/bwangk/article/details/111402909
c++11的多线程库使用方法例子,介绍了c++11和thread库的使用方法
c++11多线程库的使用,主要介绍了thread类中的构造函数 join函数和detach函数的使用方式
c++多线程库的使用demo,介绍了互斥库 mutex的使用方式
《C++面向对象多线程编程》推荐:毫无疑问,这是我见过的最好的、最全面的多线程方面的图书。如果你把自己看作一位程序员,而不是组件装配员,那你就需要了解多线程方面的知识。只要不是刚刚入门的C++程序员都可以从...
QT/C++11多线程、互斥/读写锁、多生产消费模型
线程安全队列的接口文件如下: #include template class threadsafe_queue { public: threadsafe_queue(); threadsafe_queue(const threadsafe_queue&); threadsafe_queue& operator=(const threadsafe_queue&...
本课程,讲解的重点定位在c++11新标准中的多线程开发部分,同时,老师还会结合自己的经验把多线程的讲解进一步拓展到一个比较大的范畴,因为无论是c++11多线程开发还是各种其他的多线程开发实现方法,都有很多类似的...
c++ 多线程向同一个文本写入信息 解决同步与互斥问题
c++ builder 多线程方法和实例,
面试题c++mysql多线程操作系统 面试题c++mysql多线程操作系统 面试题c++mysql多线程操作系统 面试题c++mysql多线程操作系统 面试题c++mysql多线程操作系统
C++多线程基类C++多线程基类C++多线程基类C++多线程基类C++多线程基类C++多线程基类C++多线程基类C++多线程基类C++多线程基类
非常不错,值得收藏
C++多线程SOCKET收发纯手工打造,网上的例子和解释都不行~既可以学习多线程操作,又可以实现SOCLET编程