使用C++11让多线程开发变得简单

#include <iostream>
#include <functional>
#include <map>
#include <vector>
#include <algorithm>
#include <cstring>
#include <thread>
using namespace std;
void func(){
    this_thread::sleep_for(chrono::seconds(3));
    cout << "do something" << endl;
}

int main(){
    thread t(func);
    //t.join();//函数func会运行于线程对象t中,join函数会阻塞线程,直到线程函数执行结束,如果线程函数有返回值,返回值被忽略
    //t.detach();//将线程和线程对象分离,让线程作为后台线程去执行,当前线程也不会阻塞了
    //需要注意的是detach()之后就无法再和线程发生联系了,比如detach之后就不能通过join来等待线程执行完,线程何时执行完我们也无法控制了
    thread t1(move(t));//线程移动以后,t就不存在了,这个时候就不能调用t.join()函数了。
    //t.join();-->error
    cout << t1.get_id() << endl;//获取当前线程id,22644

    cout << "timeout" << endl;
    t1.join();
    cout << t1.get_id() << endl;//获取当前线程id,0,表示已经执行结束了.
    cout << std::thread::hardware_concurrency() << endl;//8核
    return 0;
}
#include <iostream>
#include <functional>
#include <map>
#include <vector>
#include <algorithm>
#include <cstring>
#include <thread>
#include <mutex>
using namespace std;
mutex glock;
void func(){
    glock.lock();
    this_thread::sleep_for(chrono::seconds(3));
    cout << "do something" << endl;
    glock.unlock();//加锁封锁操作
}
void fun(){
    lock_guard<mutex> lock(glock);//出作用域自动解锁.
    cout << this_thread::get_id() << " works now" << endl;
    this_thread::sleep_for(chrono::seconds(3));
    cout << "do something" << endl;
}
int main(){
    thread t1(fun);
    thread t2(fun);
    thread t3(fun);
    t1.join();
    t2.join();
    t3.join();
    return 0;
}

一个线程池

#include <iostream>
#include <functional>
#include <map>
#include <vector>
#include <algorithm>
#include <cstring>
#include <thread>
#include <mutex>
using namespace std;
template <class T>
class ThreadPool{
    bool isFull() const {
        return m_queue.size() == m_maxSize;
    }
    bool isEmpty() const{
        return m_queue.empty();
    }
public:
    ThreadPool(int mSize) :m_maxSize(mSize){}
    void put(const T &value){
        unique_lock<mutex> locker(m_mutex);
        while (isFull){
            cout << "缓冲区满了" << endl;
            m_notFull.wait(locker, [this](){return !isFull()});
        }
        m_queue.push_back(value);
        m_notEmpty.notify_one();
    }
    void get(const T&x){
        unique_lock<mutex> locker(m_mutex);
        while (isEmpty){
            cout << "缓冲区为空" << endl;
            m_notEmpty.wait(locker, [this](){return !is_empty()});
        }
        x = m_queue.pop_front();
    }
    bool Empty(){
        std::lock_guard<mutex>locker(m_mutex);
        return m_queue.empty();
    }
    bool Full(){
        std::lock_guard<mutex>locker(m_mutex);
        return m_queue.size() == m_maxSize;
    }
    size_t Size(){
        std::lock_guard<mutex>locker(m_mutex);
        return m_queue.size();
    }
    int count(){
        std::lock_guard<mutex>locker(m_mutex);
        return m_queue.size();
    }
private:
    condition_variable m_notEmpty;

    mutex m_mutex; //互斥量
    int m_maxSize; //线程池最大缓冲数目
    list<T> m_queue;//缓冲区,缓冲队列

};

int main(){

    return 0;
}
#include <iostream>
#include <functional>
#include <map>
#include <vector>
#include <algorithm>
#include <cstring>
#include <thread>
#include <mutex>
#include <future>
#include <chrono>
using namespace std;


int main(){
    promise<int>pr;
    thread t([](promise<int>&p){
    p.set_value_at_thread_exit(100);
    }, ref(pr));
    t.join();
    //t.detach();必须选择一个,否则程序会发生异常,不明白为什么会发生异常.
    future<int>f = pr.get_future();
    auto i = f.get();
    cout << i << endl;

    packaged_task<int()> task([](){ return 7; });
    thread t2(ref(task));
    t2.join();
    future<int> fut = task.get_future();
    cout << fut.get() << endl;
    return 0;
}

C++11 提供了几种异步调用的方法,都能通过std::future来获取异步执行的结果。

  1. std::promise 可以用来在线程间提供数据传递。std::future = std::promise.get_future()。线程中可以对promise赋值std::promise.set_value。赋值之后std::future.get()就会返回其他线程中设置的值。

promise封装了数据和future,将数据和future绑定起来,为获取线程函数中的某一个值提供便利,在线程函数中为外面传进来的promise赋值,在线程函数执行完成以后,,就可以通过promise的get_future方法获取该值了

#include <iostream>  
#include <future>  
#include <chrono>  
std::promise<int> promis;
int main(int argc, const char * argv[]) {
    std::thread t([](std::promise<int>& promis){
        std::this_thread::sleep_for(std::chrono::seconds(10));
        promis.set_value_at_thread_exit(123);
    },ref(promis));
    t.detach();
    std::cout << "detach..." << std::endl;
    std::future<int> fuResult = promis.get_future();
    std::cout << fuResult.get() << std::endl;
    return 0;
}

2.std::packaged_task 可以包裹一个函数, 有点类似std::function,不同之处在于这个可以通过get_future返回std::future对象来获取异步执行的函数结果。
包装了一个可调用对象的包装类,如function, lambda expression, bind expression 和another function object,将函数和future绑定起来,以便异步调用。

#include <iostream>  
#include <future>  
#include <chrono>  

int main(int argc, const char * argv[]) {
    int y;
    std::cin >> y;
    std::packaged_task<int(int)> m([](int x){
        std::this_thread::sleep_for(std::chrono::seconds(10));
        return x + 100;
    });
    std::future<int> fuResult = m.get_future();
    std::thread task(std::move(m),y); //给y加100,得到返回值.
    task.detach();
    std::cout << "detach..." << std::endl;
    std::cout << fuResult.get() << std::endl;
    return 0;
}
  1. std::async提供异步执行的方法,std::future = std::async(…), 函数执行完成后可以通过std::future.get()获取到执行函数的返回值

async()叫做线程异步操作函数!!!

#include <iostream>  
#include <future>  
#include <chrono> 

int main(int argc, const char * argv[]) {

    std::future<int> fuResult = std::async([](){std::launch::async,
        std::this_thread::sleep_for(std::chrono::seconds(1));
        return 1;
    });
    std::cout << "detach..." << std::endl;
    std::cout << fuResult.get() << std::endl;
    return 0;
}
#include <iostream>  
#include <future>  
#include <chrono> 
using namespace std;
struct Base{
    void Fun()
    {
        cout << "it is fun" << endl;
    }
};
struct Derived:Base{
    using Base::Fun;//c++11新特性.
    void Fun(int a){
        cout << "it is fun in derived" << endl;
    }
};
int main() {
    Derived d;
    //d.Fun();//会产生编译错误
    d.Fun();//这样就不会出错了.
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值