C++11 线程

来源:互联网 发布:python开发网站学多久 编辑:程序博客网 时间:2024/06/02 07:53

C++11 线程

flyfish

下面示例包括

1 启动一个线程

2 带参数的线程

3 线程中使用了异步模式

4 使用lambda表达式向窗口发送消息

void f0(){    std::this_thread::sleep_for(std::chrono::seconds(3));    //输出log 表明运行到这里}void f1(int t){    std::this_thread::sleep_for(std::chrono::seconds(3));    //输出t的值}void f2(){    std::future<int> future = std::async(std::launch::async, [](){        std::this_thread::sleep_for(std::chrono::seconds(3));        int ret = 2;        return ret;    });    std::future_status status;    do {        status = future.wait_for(std::chrono::seconds(1));        if (status == std::future_status::deferred) {        }        else if (status == std::future_status::timeout) {        }        else if (status == std::future_status::ready) {        }    } while (status != std::future_status::ready);    //future.get() 输出2}

使用方式

    std::thread t0(f0);//不带参数的线程    t0.detach();    std::thread t1(f1,1);//带参数的线程    t1.detach();    std::thread t2(f2);//线程中的又启动了异步模式    t2.detach();

向对话框发送消息

对话框类头文件

afx_msg LRESULT OnFunction(WPARAM, LPARAM);

实现文件
消息映射

ON_MESSAGE(WM_USER+100, OnFunction)LRESULT 对话框类::OnFunction(WPARAM w, LPARAM l){    AfxMessageBox(L"收到自定义消息");    return 0;}

使用方式

    int i = 3;    std::thread t3([i,this]() //lambda    {               std::this_thread::sleep_for(std::chrono::seconds(i));        SendMessage(WM_USER + 100, 0, 0);    });    t3.detach();
0 0