• 23.线程锁的使用


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

    1.不应该频繁的使用锁

    2.减小锁使用的区域,线程公共资源之外 的资源 尽量不要放到临界区。

    -------------------------------------------------------------------------------------------------------

     示例一:(这样使用线程锁,设定的临界区域不合理,会让线程的调用失去意义,线程并没有并发执行)

    #include <iostream>
    #include <thread>
    #include <mutex>
    
    using namespace std;
    
    mutex m_lock;
    
    int sum = 0;
    
    void workFun(int index)
    {
        m_lock.lock();
        for (int i = 0; i < 1000; i++)
        {
            sum++;
            cout << "thread:"<<index << " sum=" << sum<<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();
        }
    
        cout << "sum=" << sum << endl;
        cout << "i am main thread " << endl;
        return 0;
    }

    ----------------------------------------------------------------------------------------------------------

    示例二:(不用线程)

    #include <iostream>
    #include <thread>
    #include <mutex>
    
    using namespace std;
    
    mutex m_lock;
    
    int sum = 0;
    
    void workFun()
    {
        
        for (int i = 0; i < 300000; i++)
        {
            sum++;
        }
        
    
    }//抢占式
    
    int main()
    {
        thread t[3];
    
        workFun();
    
        cout << "sum=" << sum << endl;
        cout << "i am main thread " << endl;
        return 0;
    }

    示例三:(使用线程,并且加锁)

    #include <iostream>
    #include <thread>
    #include <mutex>
    
    using namespace std;
    
    mutex m_lock;
    
    int sum = 0;
    
    void workFun(int index)
    {
    
        for (int i = 0; i < 100000; i++)
        {
    
            m_lock.lock();
            sum++;
            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();
        }
    
        cout << "sum=" << sum << endl;
        cout << "i am main thread " << endl;
        return 0;
    }

    示例三的耗时 会比 示例二的耗时大,所以要慎用多线程,慎用锁。设计不好的多线程反而会更耗时。

  • 相关阅读:
    WMS、WCS、PLC、AGV
    SAP消息号修改汇总
    SQL 计算累计和 sum() over( partition by order by )
    DDLS报错数据类型冲突:data type conflict in a selection 解决办法
    SAP销售订单需求类型的确定优先级
    SAP替代,出口U904在RGGBS000中未生成
    订单BOM与销售BOM的区别
    在配置和销售凭证 GET_CONFIG_MODE 间通信时内部出错
    ABAP Write
    php的api接口
  • 原文地址:https://www.cnblogs.com/zhangxuan/p/14374689.html
Copyright © 2020-2023  润新知