C++之深入解析std::thread的使用

一、C++11 线程创建

  • 每一个 C++11 程序都包含一个主线程即 main() 函数,在 C++11 中可以通过创建 std::thread 对象来创建新的线程,每个 std::thread 对象都可以与一个线程相关联。
  • 需要引用的头文件:
#include <thread>

二、std::thread 的构造函数中接收什么参数?

  • 可以给 std::thread 对象添加函数,这个回调函数将在这个新线程启动时执行。这些回调可以是:
    • 函数指针;
    • 函数对象;
    • Lambda 函数。
  • 创建 thread 对象:
std::thread thObj(<CALLBACK>);
  • 新线程将在创建新对象后立即启动,并将并行地执行(当参数)传递给线程的回调函数。此外,任何线程都可以通过调用某线程对象上的 join( ) 函数来等待此线程退出。
  • 来看一个例子,主线程将创建另外一个线程,创建这个新线程后,主线程会在控制台上打印一些数据,然后等待新创建的线程退出。
  • 使用函数指针创建线程:
#include <thread>

void thread_function() {
    for(int i = 0; i < 10000; i++);
        std::cout<<"thread function Executing"<<std::endl;
}

int main() {
    std::thread threadObj(thread_function);
    for(int i = 0; i < 10000; i++);
        std::cout<<"Display From MainThread"<<std::endl;
    threadObj.join();    
    std::cout<<"Exit of Main function"<<std::endl;
    return 0;
}
  • 使用函数对象创建线程:
#include <iostream>
#include <thread>
class DisplayThread {
public:
    void operator()() {
        for(int i = 0; i < 10000; i++)
            std::cout<<"Display Thread Executing"<<std::endl;
    }
};

int main() {
    std::thread threadObj( (DisplayThread()) );
    for(int i = 0; i < 10000; i++)
        std::cout<<"Display From Main Thread "<<std::endl;
    std::cout<<"Waiting For Thread to complete"<<std::endl;
    threadObj.join();
    std::cout<<"Exiting from Main Thread"<<std::endl;
    return 0;
}
  • 使用 Lambda 函数创建线程:
#include <iostream>
#include <thread>
int main() {
    int x = 9;
    std::thread threadObj([]{
            for(int i = 0; i < 10000; i++)
                std::cout<<"Display Thread Executing"<<std::endl;
            });

    for(int i = 0; i < 10000; i++)
        std::cout<<"Display From Main Thread"<<std::endl;

    threadObj.join();
    std::cout<<"Exiting from Main Thread"<<std::endl;
    return 0;
}
  • 如何区分线程:
    • 每个 std::thread 对象都有一个 ID,使用下面的函数可以获取:
std::thread::get_id()
    • 获取当前线程的 ID:
std::this_thread::get_id()
    • 如果 std::thread 对象没有和任何对象关联,则 get_id() 函数会返回默认构造的 std::thread::id 对象,即“非线程”。std::thread::id 是一个对象,它也可以在控制台上进行比较和打印:
#include <iostream>
#include <thread>
void thread_function() {
    std::cout<<"Inside Thread :: ID  = "<<std::this_thread::get_id()<<std::endl;    
}
int main() {
    std::thread threadObj1(thread_function);
    std::thread threadObj2(thread_function);

    if(threadObj1.get_id() != threadObj2.get_id())
        std::cout<<"Both Threads have different IDs"<<std::endl;

    std::cout<<"From Main Thread :: ID of Thread 1 = "<<threadObj1.get_id()<<std::endl;    
    std::cout<<"From Main Thread :: ID of Thread 2 = "<<threadObj2.get_id()<<std::endl;    

    threadObj1.join();    
    threadObj2.join();    
    return 0;
}

三、std::thread 的搭配用法

① std::promise

  • 为了在不同的线程之间传递数据,C++ 引入了 std::promise 和 std::future 这两种数据结构,在头文件 <future> 中包含。
  • promise 是一个范型的数据结构,你可以定义一个整形的 promise:promise,这意味着线程之间传递的值是整形。promise 的 get_future() 方法返回一个 future 数据结构,从这个 future 数据结构可以获取设置给 promise 的值:
#include <iostream>
#include <future>
#include <thread>

using namespace std;

int main() {
  promise<int> a_promise;
  auto a_future = a_promise.get_future();
  a_promise.set_value(10);
  cout << a_future.get() << endl;
  cout << "after get()" << endl;
  return 0;
}
  • 输出结构是:
10
after get()
  • 实际上,上面的例子并没有使用线程,但是很好得展示了 promise 和 future 之间的关系。更复杂一点的使用场景可能如下:
    • 主线程定义一个 promise,命名为 p;
    • 主线程调用 p.get_future(),并把返回值保存为引用 f;
    • 主线程启动一个子线程,并把 p 作为启动参数传给子线程;
    • 主线程调用 f.get(),但是此时子线程还未将数据放入 promise 内,所以主线程挂起;
    • 子线程执行完,获取到结果,并把结果写入 p;
    • 主线程从 f.get() 的调用中被唤醒,获取到子线程写入 p 的值,继续执行。

② std::packaged_task

  • C++11 很贴心地提供 packaged_task 类型,可以不用直接使用 std::thread 和 std::promise,直接就能够生成线程,派遣任务:
#include <iostream>
#include <future>

using namespace std;

int f() {
  string hi = "hello, world!";
  cout << hi << endl;
  return hi.size();
}

int main() {
  packaged_task<int ()> task(f);
  auto result = task.get_future();

  task();

  cout << result.get() << endl;

  return 0;
}
  • 运行结果为:
hello, world!
13

③ std::async

  • std::packaged_task 要求自己启动任务,比如要显示调用 task(),如果连这一步都想省了的话,可以使用 std:async:
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <future> 

template <typename RandomIt>

int parallel_sum(RandomIt beg, RandomIt end) {
    auto len = end - beg;
    if (len < 1000) 
        return std::accumulate(beg, end, 0);

    RandomIt mid = beg + len/2;
    auto handle = std::async(std::launch::async,
                             parallel_sum<RandomIt>, mid, end);
    int sum = parallel_sum(beg, mid);
    return sum + handle.get();
}

int main() {
    std::vector<int> v(10000, 1);
    std::cout << "The sum is " << parallel_sum(v.begin(), v.end()) << '\n';
}
  • 运行结果:
The sum is 10000

④ std::this_thread

  • C++11 专门提供了一个命名空间 std::this_thread 来表示当前线程。
  • std::this_thread 提供了几个方法可以对线程做一定的控制:
    • get_id(),获取线程 id;
    • yield(),释放执行权;
    • sleep_for(),使线程沉睡一定时间。
#include <iostream>
#include <future>
#include <thread>
using namespace std;

int f(promise<int> my_promise) {
  string hi = "hello, world!";

  my_promise.set_value(hi.size());

  this_thread::sleep_for(0.1s);
  cout << hi << endl;
}

int main() {
  promise<int> f_promise;

  auto result = f_promise.get_future();

  thread f_thread(f, move(f_promise));
  cout << result.get() << endl;

  f_thread.join();

  return 0;
}
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

╰つ栺尖篴夢ゞ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值