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;}