C++-BOOST(1)-线程(Thread)与互斥量(mutex)

1.线程调用两种方式:函数与类

using namespace boost;
//1.函数调用
//2.类调用
void fun()
{
    cout << "fun Hello world, I''m a fun thread!" << endl;
}
class myClassThread
{
  public:
    void fun()    //被调用的函数
    {
        cout <<   "Hello world, I''m a myClassThread!"<<endl;
    }
    void start()  //启动线程函数
    {
        boost::function0< void> f = boost::bind(&myClassThread::fun, this);
        boost::thread thrd(f);
        thrd.join();
    }

};

void myThread_main()
{
    cout << "myThread_main" << endl;

    boost::thread thrd(&fun);   //1.调用函数线程
    thrd.join();

    cout << " myClassThread" << endl;//2.调用类线程
    myClassThread m_thread;
    m_thread.start();
}

2.互斥量:2.1mutex  会阻塞线程 单独用时要try catch
                  2.2timed_mutex 超时立即返回
                  2.3 lock_guard 自动完成mutex锁定解锁操作
 

void myThread_main()
{

    //互斥变量,
    //1.1 mutex 但是会阻塞线程 单独用时要try catch
    boost::mutex mu;   
    try {
        mu.lock();                  //锁定互斥量
        cout<<"操作共享资源"<<endl; //操作共享资源
        mu.unlock();                //解锁互斥量

    }
    catch (...)
    {
        mu.unlock();
    }

    //1.2 timed_mutex 超时立即返回
    boost::timed_mutex tmu;
    auto flag = tmu.try_lock_for(100_ms);//等待100ms
    if (flag)
    {
        cout<<"lock timed_mutex"<<endl;//访问共享资源
        tmu.unlock();
    }
    //哪怕未获得解锁,也执行其他操作

     //1.3 lock_guard 自动完成mutex锁定解锁操作
     //1.3.1 与mutex同用
    boost::mutex mu2;                         //声明互斥量对象
    boost::lock_guard<boost::mutex> g(mu2);   //使用lock_guard
    cout<<"some operation"<<endl;             //访问共享资源


    //3.3.2 与timed_mutex同用
    boost::timed_mutex tmu2;                  //定义互斥量
    auto flag = tmu2.try_lock_for(100_ms);     //锁定时间为100ms
    if (flag)
    {
                        //定义互斥量
        boost::lock_guard< boost::timed_mutex> g(tmu2, boost::adopt_lock);//不会再次加锁
        cout << "lock timed_mutex" << endl;                             //访问共享资源

    }
                                                      //自动释放




}

 

原文链接: https://www.cnblogs.com/jasmineTang/p/14369244.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++-BOOST(1)-线程(Thread)与互斥量(mutex)

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/339880

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午12:19
下一篇 2023年3月2日 上午12:19

相关推荐