C++多线程Thread的使用
来源:互联网 发布:linux jdk tar.gz 编辑:程序博客网 时间:2024/06/14 20:30
std::thread
thread的构造函数支持4中函数
- 普通函数
- 函数对象
- 类的成员函数
- lamda表达式
#include <thread>#include <vector>#include <deque>#include <condition_variable>#include <mutex>void f1(int n){ printf("%d \n", n);}class ClassObject{public: void operator()(int n){ printf("%d \n", n); } void f3(int n){ printf("%d \n", n); } static void f4(int n){ printf("%d \n", n); }};auto f4 = [](int n)->void {printf("lamda %d\n", n);};std::thread t1(f1, 100); // 普通函数std::thread t2(ClassObject(), 150); // 函数对象std::thread t3(&ClassObject::f3, ClassObject(), 200); //非静态成员函数std::thread t4(&ClassObject::f4, 300); // 静态成员函数不需要传递对象std::thread t5(f4, 400); // lambda调用
lambda 表达式: [capture] (args) opt -> ret {body;};
opt可以是mutable, exception, attribute
- [=]按值捕获
- [&]按引用
- [=, , capture-list],除capture-list中的, 其他都按值捕获,
- [&, capture-list],除 capture-list中的,其他按照引用捕获
//// 生产者消费者//class ThreadDemo{private: std::deque<int> data; std::mutex mtx; std::condition_variable m_cv; int nGen; void ProductThread(){ while(true){ std::unique_lock <std::mutex> lck(mtx); nGen = ++nGen % 1000; printf("Product %d\n", nGen); data.push_back(nGen); lck.unlock(); m_cv.notify_all(); std::chrono::milliseconds dura(1000); std::this_thread::sleep_for(dura); } } void ConsumeThread(){ while (true){ std::unique_lock<std::mutex> lck(mtx); while (data.empty()){ m_cv.wait(lck); } int nData = data.front(); data.pop_back(); printf("consume %d\n", nData); lck.unlock(); std::chrono::milliseconds dura(2000); std::this_thread::sleep_for(dura); } }public: ThreadDemo(){ data.clear(); nGen = 0; } void Start(){ std::vector<std::thread> threads; threads.clear(); for(int i = 0; i < 5; i++) threads.push_back(std::thread(&ThreadDemo::ProductThread, this)); for(int i = 0; i < 10; i++) threads.push_back(std::thread(&ThreadDemo::ConsumeThread, this)); for(auto &t: threads){ t.join(); } }};int main(){ ThreadDemo test; test.Start(); return 0;}
阅读全文
0 0
- C++多线程Thread的使用
- C#Thread的使用
- C# 多线程的使用(Thread)-初识多线程
- python多线程thread/threading的使用
- <Boost> boost::thread 多线程的使用
- C#多线程Thread.Abort的使用
- C#多线程的使用(Thread)-多线程的挂起,恢复操作
- 4.多线程实例:thread.c
- 4.多线程实例:thread.c
- C#Thread类—多线程
- C#Thread 线程的简单使用
- [Python]多线程入门 --thread使用
- java多线程使用(Thread)
- java多线程:Thread.join 使用
- 多线程std::thread的使用 以及performFunctionInCocosThread函数
- C++11多线程std::thread的简单使用(上)
- C++11_多线程std::thread的使用
- C++11 多线程学习----std::thread类的简单使用
- phpcms安装完后还是会跳到install/install.php
- final关键字修饰变量,引用变量中所指向的对象中内容可变
- UVA 107
- js回调函数
- MySQL 获得当前日期时间(以及时间的转换)
- C++多线程Thread的使用
- React-Native 与原生的3种交互通信(Android)
- 【树状数组 求比其小的个数】poj 2353 Stars
- C#通过反射将DataRow转换成对应实体对象
- GoLang代码包的开发详细记录
- 安装破解idea 2017
- 点胶机对电子产品点胶注意事项?
- java中的内部类总结
- [Leetcode] 400. Nth Digit 解题报告