C++多线程学习08

参考资料

链接:恋恋风辰官方博客

复制构造or移动构造

#include <iostream>
#include <thread>
#include <memory>
#include <functional>
#include <future>

class TestCopy
{
public:
    TestCopy(){}
    TestCopy(const TestCopy& tp)
    {
        std::cout << "Test copy copy. \n";
    }
    TestCopy(TestCopy&& cp)
    {
        std::cout << "Test copy move. \n";
    }
};

TestCopy test_copy()
{
    TestCopy tp;
    return tp;
}


int main()
{
    // 1. 测试默认是移动构造还是拷贝构造
    auto obj = test_copy();      // 默认是移动构造


    std::cout << "Finished! \n";
}

测试结果:

线程归属权问题

#include <iostream>
#include <thread>
#include <memory>
#include <functional>
#include <future>


void thread_ops()
{
    std::thread t1([]() {
        int i = 0;
        while (i < 5)
        {
            std::this_thread::sleep_for(std::chrono::seconds(1));
            i++;
        }
        });

    std::thread t2([]() {
        int i = 0;
        while (i < 10)
        {
            std::this_thread::sleep_for(std::chrono::seconds(1));
            i++;
        }
        });

    t1 = std::move(t2);
    t1.join();
    t2.join();
}

int main()
{
    // 2. 线程归属权问题: 不能将线程转移给一个已经绑定的变量
    thread_ops();

    std::cout << "Finished! \n";
}

  • 11
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值