// 8:15 AM/09/28/2017
#pragma once
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex
#include <chrono>
using namespace std;
volatile int counter();
volatile int counter2();
mutex mtx;//This mutex class is synchronization primitive that
//can be used to protect shared data from being simultaneously accessed by multiple threads.
// mutex类是一个同步原语,用来保护共享数据,阻止多线程同时访问
mutex mtx2; void run()
{
for (int i = ; i < ; ++i)
{
mtx.lock();// lock mtx,blocks if mtx is not available
// the word block means that when the mtx is avaiable,it will lock mtx and the following code will being executed
++counter;
cout << this_thread::get_id() << "==> " << counter << endl; mtx.unlock();// this function will make mtx is available,
//and other threads that is being blocked will detect the mtx is available
// but the others don't mean that all of them can detect the mtx is available because if one detect it and it will lock it.
// only the one thread will own the mtx
//here the function unlock is necessary
//一般不直接使用mutex 而用 std::unique_lock, std::lock_guard等
//mutex is usually not accessed directly }
} void run2()
{
for (int i = ; i < ; i++)
{
if (mtx2.try_lock())
//It differs from the function lock.Here,it will not block and if mtx2 is available,it will be lock and return ture.
{
++counter2;
cout << this_thread::get_id() << "==> " << counter2 << endl;
mtx2.unlock();
}
}
} int main(int argc, const char* argv[])
{
thread ts[];
for (int i = ; i < ; ++i)
{
ts[i] = thread(run);
}
for (auto& t : ts) t.join(); std::this_thread::sleep_for(std::chrono::seconds());
// sleep for 2s thread ts2[];
for (int i = ; i < ; ++i)
{
ts2[i] = thread(run2);
}
for (auto& t : ts2)t.join();
}
//We see that the results of counter and counter2 are not same,and we convincingly konw the counter is equal
//to 1000 because of the function lock.The counter2,however,may not have a unique result owing to the function
// try_lock without blocking.

最新文章

  1. Bitmap转换成BitmapImage
  2. SQL Server里的闩锁耦合(Latch Coupling)
  3. MVC5 + EF6 + Bootstrap3 (16) 客户端验证
  4. [Leetcode] Roman to Integer
  5. js与jquery异同
  6. 【ASP.NET 进阶】根据IP地址进行百度地图定位
  7. 彷徨中的成长-记一个文科生的IT成长过程
  8. C# 中LinkLabel的简单使用
  9. .net远程连接oracle数据库不用安装oracle客户端
  10. lab1-Junit&amp;Eclemma
  11. 硬盘分区表格式GUID和MBR知识普及
  12. [django]用fastcgi部署
  13. shiro多Realm第一次调用不生效问题
  14. ubuntu中subline无法使用搜狗输入法
  15. python-requests数据驱动延伸
  16. 运行时类型识别RTTI
  17. fprintf宏
  18. JS框架设计之对象扩展一种子模块
  19. redis系统和通用函数
  20. maven install jdk版本自动降为1.7

热门文章

  1. PE文件格式详解(五)
  2. mysql无法启动服务,错误1067
  3. 数据可视化之powerBI技巧(十八)Power BI动态技巧:动态显示列和度量值
  4. 02 drf源码剖析之快速了解drf
  5. HangFire多集群切换及DashBoard登录验证
  6. Idea 自定义快捷代码输入 如syso =&gt; System.out.println()
  7. P1290 欧几里德的游戏(洛谷)
  8. 如何获取json某一级节点的数据
  9. OKex平台如何使用谷歌身份验证?
  10. jmeter零散知识点