这里写目录标题
1. 实验
-
简介:我们启动
并行启动两个线程
,但设置一个全局互斥锁,在两个线程中等待并占用互斥锁
,然后输出日志。 -
代码
#include <iostream> #include <thread> /* C++ 多线程库 */ #include <mutex> /* C++ 互斥锁 */ /* 定义一个全局锁子 */ std::mutex mt; /* 定义线程1 */ void thread_1() { /* 等待其他程序将这个锁解开,并以当前程序名义上锁, 在程序结束时自动解锁*/ std::lock_guard<std::mutex> guard(mt); for(int i=10; i >0 ; i--){ std::cout << "thread 1 , i = " << i << std::endl; std::this_thread::sleep_for(std::chrono::microseconds(100)); } std::cout << "thread_1 end." << std::endl; } /* 定义线程2 */ void thread_2() { /* 等待其他程序将这个锁解开,并以当前程序名义上锁, 在程序结束时自动解锁*/ std::lock_guard<std::mutex> guard(mt); for(int i=10; i >0 ; i--){ std::cout << "thread 2 , i = " << i << std::endl; std::this_thread::sleep_for(std::chrono::microseconds(100)); } std::cout << "thread_2 end." << std::endl; } int main(int argc, char const *argv[]) { std::cout << "-------------------------------- " << std::endl; /* 启动两个线程并行执行函数(注意这里已经开始运行了两个函数) */ std::thread t1(thread_1); std::thread t2(thread_2); /* 阻塞等待线程的结束标志 */ t1.join(); t2.join(); std::this_thread::sleep_for(std::chrono::seconds(20)); std::cout << "-------------------------------- " << std::endl; return 0; }
-
实验结果,
上述代码执行结果
-
如果
注释等待并占用互斥锁
,实验结果如下
2. 手动锁与手动释放
- cpp一些用法
/* 互斥所的声明 */ std::mutex mt; /* 手动上锁,上锁不成功会堵塞等待其他程序释放 */ std::unique_lock<std::mutex> lock(mt); /* 当前程序上锁后,释放锁的权限 */ lock.unlock();