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");
}
}
}
fromthreadingimportSemaphoreclassFooBar:def__init__(self,n):self.n=nself.f=Semaphore(1)self.b=Semaphore(0)deffoo(self,printFoo:"Callable[[], None]")->None:for_inrange(self.n):self.f.acquire()# printFoo() outputs "foo". Do not change or remove this line.printFoo()self.b.release()defbar(self,printBar:"Callable[[], None]")->None:for_inrange(self.n):self.b.acquire()# printBar() outputs "bar". Do not change or remove this line.printBar()self.f.release()
classFooBar{privateintn;privateSemaphoref=newSemaphore(1);privateSemaphoreb=newSemaphore(0);publicFooBar(intn){this.n=n;}publicvoidfoo(RunnableprintFoo)throwsInterruptedException{for(inti=0;i<n;i++){f.acquire(1);// printFoo.run() outputs "foo". Do not change or remove this line.printFoo.run();b.release(1);}}publicvoidbar(RunnableprintBar)throwsInterruptedException{for(inti=0;i<n;i++){b.acquire(1);// printBar.run() outputs "bar". Do not change or remove this line.printBar.run();f.release(1);}}}
#include<semaphore.h>classFooBar{private:intn;sem_tf,b;public:FooBar(intn){this->n=n;sem_init(&f,0,1);sem_init(&b,0,0);}voidfoo(function<void()>printFoo){for(inti=0;i<n;i++){sem_wait(&f);// printFoo() outputs "foo". Do not change or remove this line.printFoo();sem_post(&b);}}voidbar(function<void()>printBar){for(inti=0;i<n;i++){sem_wait(&b);// printBar() outputs "bar". Do not change or remove this line.printBar();sem_post(&f);}}};