刷leetcode:1114题以及相应的解法
给你一个类:
public class Foo
{
public void first() { print("first"); }
public void second() { print("second"); }
public void third() { print("third"); }
}
三个不同的线程 A、B、C 将会共用一个 Foo 实例。
线程 A 将会调用 first() 方法
线程 B 将会调用 second() 方法
线程 C 将会调用 third() 方法
请设计修改程序,以确保 second() 方法在 first() 方法之后被执行,third() 方法在 second() 方法之后被执行。
解法一:原子操作
多线程随机调用的过程中确保按照:first()---->second()------>third()的顺序执行方法。可以利用atomic count的原子性,无需加锁操作; 初始化count=0,
(1)当count%N等于0(N为方法数量,N=3)执行first()后count++,
(2) 当count%N等于1时执行second() 后count++
(3) 当count%N等于2时执行third() count++;
这样就能按照徐打印了,而且可以方法数量可以不断增加和拓展
// An highlighted block
#include<mutex>
#include<thread>
#include<iostream>
#include<unistd.h>
using namespace std;
class Foo {
public:
Foo() {
}
void first(function<void()> printFirst) {
while(count%3!=0) usleep(50);
// printFirst() outputs "first". Do not change or remove this line.
printFirst();
count++;
}
void second(function<void()> printSecond) {
while(count%3!=1) usleep(50);
// printSecond() outputs "second". Do not change or remove this line.
printSecond();
count++;
}
void third(function<void()> printThird) {
while(count%3!=2) usleep(50);
// printThird() outputs "third". Do not change or remove this line.
printThird();
count++;
}
private:
std::atomic<int> count{0};
};
解法二:互斥锁
多线程随机调用的过程中确保按照:first()---->second()------>third()的顺序执行方法。利用mutex只有一个线程能够占有临界资源,将mutex资源初始化后,设置为mtx.lock()状态,second()方法里面加入mtx.lock()操作,其他方法要执行必须unlock之后,在first()里面加入mtx.unlock()操作,这样只有first()执行后,second方法才能执行。三种方法的依次执行用两把锁就可以实现了。
// An highlighted block
#include<mutex>
#include<thread>
#include<iostream>
#include<unistd.h>
using namespace std;
class Foo {
public:
Foo() {
mtx1.lock();
mtx2.lock();
}
void first(function<void()> printFirst) {
//while(count%3!=0) usleep(50);
// printFirst() outputs "first". Do not change or remove this line.
printFirst();
//count++;
mtx1.unlock();
}
void second(function<void()> printSecond) {
//while(count%3!=1) usleep(50);
// printSecond() outputs "second". Do not change or remove this line.
mtx1.lock();
printSecond();
mtx1.unlock();
mtx2.unlock();
//count++;
}
void third(function<void()> printThird) {
//while(count%3!=2) usleep(50);
// printThird() outputs "third". Do not change or remove this line.
mtx2.lock();
printThird();
mtx2.unlock();
//count++;
}
private:
//std::atomic<int> count{0};
mutex mtx1;
mutex mtx2;
};
1595

被折叠的 条评论
为什么被折叠?



