新线程的回调函数也可以是有一个Lambda表达式的形式

来源:互联网 发布:网上买钻戒靠谱吗 知乎 编辑:程序博客网 时间:2024/05/07 19:11
#include <thread>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<thread> threads;//使用vector来存放每个线程,线程的回调函数通过Lambda表达式产生,注意后面join的使用方式。
    for (int i = 0; i < 5;++i)//C++11支持Lambda表达式,因此一个新线程的回调函数也可以是有一个Lambda表达式的形式,但是注意如果使用Lambda表达式最好不要使用引用的方式,应该使用值传递的方式来访问数据,在多线程中使用引用容易造成混乱。
    {
        threads.push_back(thread([]()//创建了多个子线程,并使用了get_id()方法来获取当前线程的id。
        {
            cout << "Hello from lamda thread" << this_thread::get_id() << endl;
            
        }));
    }
    for (auto& thread:threads)
    {
        thread.join();
    }
    cout << "Main Thread" << "\t" << this_thread::get_id() << endl;

    system("pause");
    return 0;
}

#include <thread>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<thread> threads;//使用vector来存放每个线程,线程的回调函数通过Lambda表达式产生,注意后面join的使用方式。
    for (int i = 0; i < 5;++i)//C++11支持Lambda表达式,因此一个新线程的回调函数也可以是有一个Lambda表达式的形式,但是注意如果使用Lambda表达式最好不要使用引用的方式,应该使用值传递的方式来访问数据,在多线程中使用引用容易造成混乱。
    {
        threads.push_back(thread([]()//创建了多个子线程,并使用了get_id()方法来获取当前线程的id。
        {
            cout << "Hello from lamda thread" << this_thread::get_id() << endl;
            
        }));
        threads[i].join();
    }
    cout << "Main Thread" << "\t" << this_thread::get_id() << endl;

    system("pause");
    return 0;
}
0 0
原创粉丝点击