这看起来很有趣,所以我写了一些代码。虽然还没有测试它,所以可能搞砸了一些东西,但它足以证明我的想法。
typedef enum {
none = -1,
male = 0,
female = 1
} sex_t;
class Human {
public:
const sex_t id;
Human(sex_t id_) : id(id_) {assert(id != none);}
};
class Restroom {
tbb::spin_mutex door_mutex;
tbb::atomic<size_t> num_waiting;
HANDLE opposite_sex_can_enter;
// these two variables need not be atomic, they're not accessed concurrently
sex_t current_occupying_sex;
size_t num_visitors;
public:
Restroom() : current_occupying_sex(none), num_visitors(0) {
num_waiting = 0;
opposite_sex_can_enter = CreateEvent(0, TRUE, FALSE, 0);
}
void enter(const Human& h) {
tbb::spin_mutex::scoped_lock lock(door_mutex);
// this prevents any two humans trying to open the door (in any direction) at the same time :)
if(current_occupying_sex == none) {
// you're the first one in, so update the 'restroom id' and enter
assert(num_visitors == 0 && num_waiting == 0);
// if the knowledge of SetEvent has not propagated all the way yet and the same sex
// person happens to walk into the restroom again, opposite sex people need to know
// that they were slow and will need to wait again
ResetEvent(opposite_sex_can_enter);
current_occupying_sex = h.id;
++num_visitors;
} else if(h.id == current_occupying_sex) {
// you're not the first one in, but you're of the same sex, so you can just walk in
assert(num_visitors > 0);
++num_visitors;
} else {
// you're not the first one in and you're of opposite sex, so you'll need to wait
// first, let go of the door, you're not getting in :)
lock.release();
// then join the rest of the opposite sex people waiting
++num_waiting;
WaitForSingleObject(opposite_sex_can_enter);
--num_waiting;
if(num_waiting == 0) {
ResetEvent(opposite_sex_can_enter);
}
enter(h);
}
}
void exit() {
tbb::spin_mutex::scoped_lock lock(door_mutex);
if(--num_visitors == 0) {
current_occupying_sex = none;
SetEvent(opposite_sex_can_enter);
// fairness can be imposed here, meaning that if you're the last say, male
// to walk out, you can check if females are waiting and switch the
// restroom sex id to female. The logic of enter() will change a little bit, but not radically.
}
}
};