1 测试是否可以不同线程交替lock unlock
- 测试结果 成功
#include <thread>
#include <iostream>
#include <string>
#include <chrono>
#include <assert.h>
#include <mutex>
/*
测试 线程1 是否可以对 线程2 lock住的mutex 进行unlock 结果似乎可以
另一个例子
https://leetcode-cn.com/problems/print-in-order/solution/jian-dan-cu-bao-de-jie-fa-by-cai-ji-114/
*/
using namespace std;
mutex mtx;
void mylock()
{
mtx.lock(); //想象成p操作
cout << "thread lock: mtx.lock(); then sleep for 2 seconds" << endl;
this_thread::sleep_for(std::chrono::seconds(2));
}
void myunlock()
{
//cout << "thread unlock: sleep for 2 seconds" << endl;
mtx.unlock(); //想象成v操作
//mtx.lock();
cout << "thread unlock: mtx.unlock();" << endl; //after sleep for 2 seconds,
}
int main()
{
thread t1 = thread(mylock);
thread t2 = thread(myunlock);
t1.join();
t2.join();
return 0;
}
2 力扣上面的一道C++多线程题目实例
- 印证了上面的想法?
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
/*
两个不同的线程将会共用一个 FooBar 实例。其中一个线程将会调用 foo() 方法,另一个线程将会调用 bar() 方法。
请设计修改程序,以确保 "foobar" 被输出 n 次。
示例 1:
输入: n = 1
输出: "foobar"
解释: 这里有两个线程被异步启动。其中一个调用 foo() 方法, 另一个调用 bar() 方法,"foobar" 将被输出一次
来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/print-foobar-alternately
begin time : 2020 0826 20:50
end time : 2020 0826 21:18
分析:
//首先 二者肯定是需要一个 mutex print_mutex 来 实现打印互斥 mutual exclusion
// 不需要了,下面两个交替的 同步信号量 保证了 print 是串行进行的
其次 需要 同步 设置两个用于同步的信号量 mutex foo_ready bar_ready
从foo开始
二者交替
*/
/* 力扣题解
class FooBar {
private:
int n;
mutex foo_ready;
mutex bar_ready;
public:
FooBar(int n) {
this->n = n; //换成初始化列表中 对n赋值 更好,注意细节
foo_ready.lock();
}
void foo(function<void()> printFoo) {
for (int i = 0; i < n; i++)
{
bar_ready.lock();
// printFoo() outputs "foo". Do not change or remove this line.
printFoo();
foo_ready.unlock();
}
}
void bar(function<void()> printBar) {
for (int i = 0; i < n; i++)
{
foo_ready.lock();
// printBar() outputs "bar". Do not change or remove this line.
printBar();
bar_ready.unlock();
}
}
};
*/
int print_times = 0;
mutex foo_ready;
mutex bar_ready;
void foo()
{ //究极问题在于 mutex 并不存在 通知 这一说法??
//存在问题1 执行顺序92-81 82 83-93固然美好 但是 也有可能92-81 82 83-81 82 83??
//↑↑↑↑↑↑↑ 但是 这个程序很正常的按照预期运行了 奇怪
for (int i = 0; i < print_times; i++)
{
bar_ready.lock();
cout << "foo";
foo_ready.unlock();
}
}
void bar()
{
for (int i = 0; i < print_times; i++)
{
foo_ready.lock();
cout << "bar";
bar_ready.unlock();
}
}
int main()
{
foo_ready.lock();
cin >> print_times;
thread t1(foo);
thread t2(bar);
t1.join();
t2.join();
return 0;
}