• BOOST 条件变量使用


    代码:

      // boost库 条件变量 使用测试 
    
    #include <iostream>
    #include <boost/thread.hpp>
    using namespace std;
    
    boost::condition_variable cond;        //关联多个线程的条件变量
    boost::mutex mutex;             //保护共享资源的互斥体
    int k=0;                    //作为共享资源
     
    void func1(const int &id)
    {
        boost::unique_lock<boost::mutex> lock(mutex); //   m->lock();
    
        cout << "thread #hi#" << id << endl;
    
        #if 1
            static int i = 0;
            if(i++ == 1) // 第二个线程执行本函数,我就上锁两次,应该会锁死第二个线程自身。
                boost::unique_lock<boost::mutex> lock_again(mutex); // m->lock();
        #endif
    
            cout << "func1, k = " << k << endl;
        while(k<5)
        {
            cout << "thread #" << id << " : k<5, waiting..." << endl;
            cond.wait(lock); 
        }
        cout << "thread #" << id << " : now k>5, printing..." << endl;
    }
    void func2(const int &id)
    {
        cout << "thread #hi#" << id << endl;
        boost::unique_lock<boost::mutex> lock(mutex);
            cout << "func2, k = " << k << endl;
        cout << "thread #" << id << " : k will be changed..." << endl;
        k+=5; // 模拟操作共享资源 , 在锁的保护下,此时生产者是独占性操作共享资源
        
        cond.notify_all();//唤醒所有的等待线程
        //cond.notify_one();//只会唤醒一个等待线程
    }
    
    
    int main()
    {
        // 这个线程应该会顺利执行完毕
        boost::thread t1(func1, 1);
            boost::this_thread::sleep(boost::posix_time::seconds(1));
    
        // 这个线程内,上锁两次,应该会锁死本线程
        boost::thread t2(func1, 2);
    
        // 那么主线程还能继续向下执行吗  实测说话
        // 实测能继续向下执行,
        //实测,使用boost库的互斥锁和linux上的一模一样
            cout << "go on" << endl;
            boost::this_thread::sleep(boost::posix_time::seconds(1));
    
        // 同理,也锁死
        boost::thread t3(func2, 3);
    
        t1.join();
        t2.join();
        t3.join();
            cout << "---end---" << endl;
        return 0;
    }

    makefile:

    .PHONY: DOIT
    
    DOIT:
        mips-linux-gnu-g++ -I.  thread_pack.cpp -L./lib  -lboost_thread -lboost_system -o boost_app

    实测结论: 使用基于boost库的互斥锁、条件变量,和基于linux的原生API,效果一模一样。 

    .

    /************* 社会的有色眼光是:博士生、研究生、本科生、车间工人; 重点大学高材生、普通院校、二流院校、野鸡大学; 年薪百万、五十万、五万; 这些都只是帽子,可以失败千百次,但我和社会都觉得,人只要成功一次,就能换一顶帽子,只是社会看不见你之前的失败的帽子。 当然,换帽子决不是最终目的,走好自己的路就行。 杭州.大话西游 *******/
  • 相关阅读:
    Newtonsoft.Json.SerializeObject 转换参数
    EntityFramework Code First 特性
    删除SVN
    C# 数据库连接字符串
    javascript 计算后 无聊的小数点处理
    python index 自己实现
    springcloud 网关过滤器Zuul Filter
    Spring Cloud Feign服务通信与负载均衡机制
    Spring Cloid Ribbon服务的通信与负载均衡搭建
    spring-cloud注册中心集群
  • 原文地址:https://www.cnblogs.com/happybirthdaytoyou/p/13841420.html
Copyright © 2020-2023  润新知