第八章 使用可调用对象

版权声明:本文为博主原创文章,转载时请注明来源。有问题请e-mail:[email protected] https://blog.csdn.net/u011177305/article/details/52227853

本章节将会讨论创建线程的一些方法,在代码清单中已经注释。

  

代码清单:

#include<iostream>

#include<string>

#include<thread>

#include<mutex>

  

#include<future>

  

using namespace std;

  

class A

{

public:

void f(int x, char y) {} //成员函数f()

int operator()(int N) { //重载运算符

return 0;

  

}

};

  

void fool(int n){ }

  

int main()

{

A a; //实例化a

std::thread t1(a, 6); //直接使用thread,传递a的拷贝给子线程

std::thread t2(std::ref(a), 6);//传递a的引用给子线程

std::thread t3(std::move(a), 6);//此方式将a给移动到次线程,主线程中不存在/不在有效

std::thread t4(A(), 6);//传递临时创建的a对象给子线程

  

std::thread t5(fool, 6);//通过传递函数名来调用

std::thread t6([](int x) {return x*x; }, 6);//也可是使用lambda函数

  

std::thread t7(&A::f, a, 8, 'w');//通过传递a的拷贝的成员函数给子线程

std::thread t8(&A::f, &a, 8, 'w');//传递a的地址的成员函数给子线程

  

  

std::async(std::launch::async,a,6);//使用async,这也算一种

  

return 0;

}

猜你喜欢

转载自blog.csdn.net/u011177305/article/details/52227853
今日推荐