• c++的thread小测试


    windows环境还用不了thread,得下一些mingw,弄了半天没弄好,直接用了商店中心就有的Ubuntu了,但是sudo install g++出现了下载不了的问题,解决方案:https://blog.csdn.net/qq_35451572/article/details/79516563

    说几个函数:

    • thread.join()是阻塞模式,就是这个线程不跑完,下个不动。
    • thread.detach()与上个相反。
    • mutex.lock()是个死循环的锁。

    单纯的多线程

    long long x = 0;
    void t(int num){
        for(int i = 1; i <= 1000000; i++){
            x++;
        }
        cout << num << ' ' << x << '
    ';
    }
    
    int main(){
        for(int i = 1; i <= 10; i++){
            thread th(t, i);
            th.detach();
        }
        string t; cin >> t;
        cout << "tot " << x << endl;
        cin >> t;
        return 0;
    }

    测试结果:

    6 946759
    2 1049349
    4 1056640
    9 1100205
    1 1166397
    3 1231131
    5 1294207
    7 1356112
    8 2101257
    10 2113748
    asf
    tot 2113748
    dsf

    加锁的多线程

    mutex flag;
    long long x = 0;
    void t(int num){
        flag.lock();
        for(int i = 1; i <= 1000000; i++){
            x++;
        }
        cout << num << ' ' << x << '
    ';
        flag.unlock();
    }
    
    int main(){
        for(int i = 1; i <= 10; i++){
            thread th(t, i);
            th.detach();
        }
        string t; cin >> t;
        cout << "tot " << x << endl;
        cin >> t;
        return 0;
    }

    测试结果:

    1 1000000
    2 2000000
    3 3000000
    4 4000000
    5 5000000
    6 6000000
    7 7000000
    8 8000000
    9 9000000
    10 10000000
    asd
    tot 10000000
    asd
  • 相关阅读:
    用TextKit实现表情混排
    IOS类似9.png
    iphone 弹出键盘,文本框自动向上移动。
    IOS截取部分图片
    IOS给图片增加水印(图片、文字)
    iOS界面设计切图小结
    table tr th td thead tbody tfoot
    怎样让table没有边框
    margin、padding,border默认值
    Java 随机数
  • 原文地址:https://www.cnblogs.com/philo-zhou/p/14481846.html
Copyright © 2020-2023  润新知