ProDeveloperTutorial.com

教程和编程解决方案
菜单
  • Shell脚本
  • 系统设计
  • Linux系统编程
  • 4g LTE
  • 编码问题
  • C
  • C ++
  • DSA
  • GIT

C ++ 11功能:C ++多线程第5章:Mutex尝试C ++线程锁定

前开发者教程 2020年2月26日

在上一章中,我们学习了互斥。在本章中,我们将学习互斥锁中的try_lock成员函数。

如前面的语句中所述,try_lock是互斥量类的成员函数。可以使用不同类型的try_lock函数。他们是:

有9种不同的try_lock成员函数可用:

 

1. std :: try_lock
2. std :: mutex :: try_lock
3. std :: timed_mutex :: try_lock
4. std :: recursive_mutex :: try_lock
5. std :: shared_timed_mutex :: try_lock
6. std :: recursive_timed_mutex :: try_lock
7. std :: unique_lock :: try_lock
8. std :: shared_mutex :: try_lock
9. std :: shared_lock :: try_lock

在本章中,我们将学习第二种变体,即 “std::mutex::try_lock”.

1. try_lock() is a non blocking call.
2. try_lock() tries to lock the mutex.
3.成功锁定后,它将返回true,否则将返回false。

 

现在之间有什么区别“lock()”我们在上一章中看到的“try_lock()”?

当第二个线程调用“lock()”功能,如果“lock()”如果被前一个线程获取,则第二个线程将被阻塞,直到第一个线程解锁资源为止。这是一个阻止呼叫。

但是随着“try_lock()”,如果第二个线程试图获取锁,但该锁已被其他线程获取,则第二个线程将立即返回。因此,这是一个非阻塞调用。

注意:

If “try_lock()”如果在拥有互斥锁的同一线程上调用,则会导致未定义的行为。

这是因为,这将是一个死锁情况。

互斥锁:: try_lock的示例

#include <iostream>
#include <mutex>
#include <thread>

// for more tutorial in C ++ visit www.prodevelopertutorial.com

using namespace std;

int count = 0;

std::mutex mu;

void incrementCount()
{
    if (mu.try_lock()) // try_lock()
    {
   		count++;//critial section
   		cout<<count<<endl;
   
   		mu.unlock();
   	}
}

int main(void)
{
    std::thread t1(incrementCount);
    std::thread t2(incrementCount);
    std::thread t3(incrementCount);

    t1.join();
    t2.join();
    t3.join();
    
    
    return 0;
}

该网站上可用的教程列表:

C编程20+章C ++编程80+章
100多个编码问题数据结构和算法85+章
系统设计20+章Shell脚本编写12章
4g LTE 60+章节最常见的编码问题
5G NR 50+章Linux系统编程20+章
分享
电子邮件
鸣叫
领英
Reddit
绊倒
Pinterest的
上一篇文章
下一篇

关于作者

前开发者教程

每天我们都会讨论竞争性编程问题,请加入我们的网站:   电报频道

ProDeveloperTutorial.com

教程和编程解决方案
版权© 2020 ProDeveloperTutorial.com
从以下课程获得热门课程: 教育性的



      1. <figure id="GsOmIfZ" class="GJOgapa"><input id="iP6wADa"><wbr id="QqY7akd"></wbr></input></figure>