• 21.多线程-锁与临界区域


    不合理的设定临界区域,会让线程的调用失去意义。

    代码一:

    #include <iostream>
    #include <thread>
    #include <mutex>
    
    using namespace std;
    
    mutex m_lock;
    
    void workFun(int index)
    {
    
        for (int i = 0; i < 100; i++)
        {
            m_lock.lock();
            //临界区域-开始
            cout << index << " child thread " << i << endl;
            //临界区域-结束
            m_lock.unlock();
        }
    }//抢占式
    
    int main()
    {
        thread t[3];
        for (int n = 0; n<3; n++)
        {
            t[n] = thread(workFun, n);
        }
    
        for (int n = 0; n<3; n++)
        {
            t[n].join();
        }
    
        for (int i = 0; i<4; i++)
            cout << "i am main thread " << i << endl;
        return 0;
    }

    代码二:

    #include <iostream>
    #include <thread>
    #include <mutex>
    
    using namespace std;
    
    mutex m_lock;
    
    void workFun(int index)
    {
        m_lock.lock();
        //临界区域-开始
        for (int i = 0; i < 100; i++)
        {
            cout << index << " child thread " << i << endl;
        }
        //临界区域-结束
        m_lock.unlock();
    
    }//抢占式
    
    int main()
    {
        thread t[3];
        for (int n = 0; n<3; n++)
        {
            t[n] = thread(workFun, n);
        }
    
        for (int n = 0; n<3; n++)
        {
            t[n].join();
        }
    
        for (int i = 0; i<4; i++)
            cout << "i am main thread " << i << endl;
        return 0;
    }

    代码二,会让 t[0] t[1]  t[2] 这三个线程不再并行,而是顺序执行。这样就失去了调用线程的意义。

  • 相关阅读:
    2.vi 和 vim 编辑器
    1.Linux文件及目录结构
    关于聚集表的学习
    一个完整的表维护程序
    转换函数CONVERSION_EXIT_TSTRN_OUTPUT
    ABAP常用字符串处理
    函数中的异常参数设计
    数据元素文本增强(修改标准数据元素描述)
    锁对象的维护
    在物理表中分配搜索帮助
  • 原文地址:https://www.cnblogs.com/zhangxuan/p/14373392.html
Copyright © 2020-2023  润新知