0%

简单的C++线程:锁粒度、线程的交换、线程的移动

2020年5月17日 上午12:12

总结:

  1. 线程的交换和线程的转移,其实与我们平常的变量的交换混合移动是一模一样的,线程也是一个对象,那么我们就可以按照对象的处理方式处理它
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    // Demo9-11.cpp : 定义控制台应用程序的入口点。
    #include "stdafx.h"

    #include <iostream>
    #include <thread>
    #include <mutex>
    using namespace std;


    // 存钱
    void Deposit(mutex& m, int& money)
    {
    // 锁的粒度尽可能的最小化
    for(int index = 0; index < 100; index++)
    {
    m.lock();
    money += 1;
    m.unlock();
    }
    }
    // 取钱
    void Withdraw(mutex& m, int& money)
    {
    // 锁的粒度尽可能的最小化
    for (int index = 0; index < 100; index++)
    {
    m.lock();
    money -= 2;
    m.unlock();
    }
    }

    int main()
    {
    // 银行存取款
    //int money = 2000;
    //mutex m;
    //cout << "Current money is: " << money << endl;
    //thread t1(Deposit, ref(m), ref(money));
    //thread t2(Withdraw, ref(m), ref(money));
    //t1.join();
    //t2.join();
    //cout << "Finally money is: " << money << endl;

    //线程交换
    //thread tW1([]()
    //{
    // cout << "ThreadSwap1 " << endl;
    //});
    //thread tW2([]()
    //{
    // cout << "ThreadSwap2 " << endl;
    //});
    //cout << "ThreadSwap1' id is " << tW1.get_id() << endl;
    //cout << "ThreadSwap2' id is " << tW2.get_id() << endl;

    //cout << "Swap after:" << endl;
    //swap(tW1, tW2);
    //cout << "ThreadSwap1' id is " << tW1.get_id() << endl;
    //cout << "ThreadSwap2' id is " << tW2.get_id() << endl;
    //tW1.join();
    //tW2.join();

    //// 线程移动
    thread tM1( []() { ; } );
    //tM1.join();
    cout << "ThreadMove1' id is " << tM1.get_id() << endl;
    cout << "Move after:" << endl;
    thread tM2 = move(tM1);
    cout << "ThreadMove2' id is " << tM2.get_id() << endl;
    cout << "ThreadMove1' id is " << tM1.get_id() << endl;
    tM2.join();

    return 0;
    }