#1115
Medium Concurrency Print foobar alternately
Concurrency
72.1% acceptance
Feb 22, 2026
753
60
Suppose you are given the following code:
class FooBar {
public void foo() {
for (int i = 0; i < n; i++) {
print("foo");
}
}
public void bar() {
for (int i = 0; i < n; i++) {
print("bar");
}
}
}
The same instance of FooBar will be passed to two different threads:
thread A will call foo(), while
thread B will call bar().
Modify the given program to output "foobar" n times.
Solution
Rust
Time O(n²)
Space O(n)
pub struct FooBar {
n: usize,
state: Arc<(Mutex<bool>, Condvar)>, // true = foo's turn
}
impl FooBar {
pub fn new(n: usize) -> Self {
FooBar {
n,
state: Arc::new((Mutex::new(true), Condvar::new())),
}
}
pub fn foo<F: Fn()>(&self, print_foo: F) {
let (lock, cvar) = &*self.state;
for _ in 0..self.n {
let mut is_foo = lock.lock().unwrap();
while !*is_foo { is_foo = cvar.wait(is_foo).unwrap(); }
print_foo();
*is_foo = false;
cvar.notify_all();
}
}
pub fn bar<F: Fn()>(&self, print_bar: F) {
let (lock, cvar) = &*self.state;
for _ in 0..self.n {
let mut is_foo = lock.lock().unwrap();
while *is_foo { is_foo = cvar.wait(is_foo).unwrap(); }
print_bar();
*is_foo = true;
cvar.notify_all();
}
}
}