无码av一区二区三区无码,在线观看老湿视频福利,日韩经典三级片,成 人色 网 站 欧美大片在线观看

歡迎光臨散文網(wǎng) 會員登陸 & 注冊

c++多個線程函數(shù)對同一變量操作,如何枷鎖

2023-04-04 10:45 作者:大衣哥編程  | 我要投稿
  • 每個線程用不同的線程函數(shù)
    例如:
    std::mutex mutex_;
    void func1()
    {
    ??? std::cout << "func1" << std::endl;
    ??? std::lock_guard<std::mutex> lck(mutex_);
    ??? std::this_thread::sleep_for(std::chrono::seconds(7));
    ??? std::cout << "func1 end" << std::endl;
    }

    void func2()
    {
    ??? std::cout << "func2" << std::endl;
    ??? std::lock_guard<std::mutex> lck(mutex_);
    ??? std::cout << "func2 coming" << std::endl;
    ??? std::this_thread::sleep_for(std::chrono::seconds(3));
    ??? std::cout << "func2 end" << std::endl;
    }

    int main()
    {
    ??? std::thread t1(func1);
    ??? std::this_thread::sleep_for(std::chrono::seconds(2));
    ??? std::thread t2(func2);
    ??? std::this_thread::sleep_for(std::chrono::seconds(15));
    }
    由于我們在定義t1線程后,休眠了2秒,則基本可以保證:func1函數(shù) 執(zhí)行到定義鎖且到了睡眠7秒的地方了,此時線程2才開始,
    由于線程1先獲取到鎖且睡眠7秒,因此:線程2必須等7秒后才能輸出 func2 coming

  • 多個線程公用一個線程函數(shù)

    int counter = 0;
    void increase(int count) {
    ??? for (size_t i = 0; i < count; i++)
    ??? {
    ??????? /*std::lock_guard<std::mutex> lck(mutex_);*/
    ??????? std::this_thread::sleep_for(std::chrono::milliseconds(1));
    ??????? counter++;
    ??? }
    }

    測試:std::thread t1(increase, 5000);
    ??? std::thread t2(increase, 5000);
    ??? t1.join();
    ??? t2.join();
    ??? std::this_thread::sleep_for(std::chrono::seconds(5));
    ??? std::cout << "counter:" << counter << std::endl;

    結(jié)果:counter值并不是10000,說明了2個線程函數(shù)執(zhí)行時有對同counter變量修改存在問題,執(zhí)行3次結(jié)果都不同:

于是:通過枷鎖,來實現(xiàn)互斥訪問:
for (size_t i = 0; i < count; i++)
??? {
??????? std::lock_guard<std::mutex> lck(mutex_);
??????? std::this_thread::sleep_for(std::chrono::milliseconds(1));
??????? counter++;
??? }執(zhí)行3次結(jié)果如下,均為10000:

當然了,也可以在2個線程函數(shù)里執(zhí)行,枷鎖后效果一樣的。

c++多個線程函數(shù)對同一變量操作,如何枷鎖的評論 (共 條)

分享到微博請遵守國家法律
确山县| 昭苏县| 太原市| 广元市| 永仁县| 尼玛县| 安仁县| 青岛市| 抚松县| 清苑县| 鄂伦春自治旗| 武安市| 刚察县| 仪陇县| 高阳县| 西华县| 江油市| 达尔| 马山县| 珲春市| 洛隆县| 黎川县| 称多县| 济源市| 孝昌县| 焉耆| 崇义县| 桓仁| 晋江市| 林芝县| 岳西县| 奉节县| 漠河县| 溆浦县| 安塞县| 普陀区| 偃师市| 嘉黎县| 曲周县| 江达县| 阳西县|