C++11 并发指南二(std::thread 详解)

std::thread在<thread>头文件中声明,因此使用std::thread时包含<thread>头文件

1、std::thread构造:

1)default——thread():默认构造函数,创建一个空的thread执行对象

2)initialization——thread(a,b):初始化构造函数,创建一个thread对象,该对象可被joinable,新产生的线程会调用a函数,函数的参数由b给出

3)copy[deleted]——thread(const thread& ) = delete:拷贝构造函数禁用,意味着thread不可被拷贝构造

4)move——thread(thread&& x)noexcept:构造函数,调用成功后x不代表任何thread执行对象

注意:可被joinable的thread对象必须在它们销毁之前被主线程join,或者将其设置为detached

std::thread各种构造函数例子如下:

#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>
 
void f1(int n)
{
    for (int i = 0; i < 5; ++i) {
        std::cout << "Thread 1 executing\n";
        ++n;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}
 
void f2(int& n)
{
    for (int i = 0; i < 5; ++i) {
        std::cout << "Thread 2 executing\n";
        ++n;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}
 
int main()
{
    int n = 0;
    std::thread t1; // t1 is not a thread
    std::thread t2(f1, n + 1); // pass by value
    std::thread t3(f2, std::ref(n)); // pass by reference
    std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread
    t2.join();
    t4.join();
    std::cout << "Final value of n is " << n << '\n';
}
在Mac下打印结果是这样的

TThhrreeaadd  21  executing
executing
TThhrreeaadd  21 executing
 executing
Thread 1 executing
Thread 2 executing
TThhrreeaadd  12  eexxeeccuuttiinngg

Thread 1 executing
Thread 2 executing
Final value of n is 5

2、Move赋值操作

1)move——thread&  operator=(thread&& rh s) noexcept;move赋值操作,如果当前对象不可joinable,需要传递一个右值引用给move赋值操作,如果当前对象可被joinable,则terminate()报错。
2)copy[deleted]——thread&  operator=(const  thread&) = delete;拷贝赋值操作被禁用,thread对象不可被拷贝
#include <stdio.h>
#include <stdlib.h>
#include <chrono>
#include <iostream>
#include <thread>
using namespace std;

void thread_task(int n)
{
    this_thread::sleep_for(chrono::seconds(n));
    cout << "hello thread " << this_thread::get_id() << " Pause " << n << " seconds" << endl;
}

int main(void)
{
    std::thread threads[5];
    cout << "Spawning 5 threads...\n";
    for(int i = 0;i < 5; i++)
    {
        threads[i] = std::thread(thread_task,i+1);
    }
    cout << "Done spawning threads! Now wait for them to join\n";
    for(auto& t : threads)
    {
        t.join();
    }
    cout << "All threads joined.\n";
    
    return EXIT_SUCCESS;
    
}

3、其它成员函数

1)get_id:获取线程ID
2)joinable:检测线程是否可被join
3)join:join线程,会和主线程
4)detach:detach线程,与主线程分离
5)swap:swap线程
6)native_handle:返回native_handle
7)hardware_concurrency[static]:检测硬件并发特性















  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值