fromthreadingimportSemaphoreclassZeroEvenOdd:def__init__(self,n):self.n=nself.z=Semaphore(1)self.e=Semaphore(0)self.o=Semaphore(0)# printNumber(x) outputs "x", where x is an integer.defzero(self,printNumber:'Callable[[int], None]')->None:foriinrange(self.n):self.z.acquire()printNumber(0)ifi%2==0:self.o.release()else:self.e.release()defeven(self,printNumber:'Callable[[int], None]')->None:foriinrange(2,self.n+1,2):self.e.acquire()printNumber(i)self.z.release()defodd(self,printNumber:'Callable[[int], None]')->None:foriinrange(1,self.n+1,2):self.o.acquire()printNumber(i)self.z.release()
classZeroEvenOdd{privateintn;privateSemaphorez=newSemaphore(1);privateSemaphoree=newSemaphore(0);privateSemaphoreo=newSemaphore(0);publicZeroEvenOdd(intn){this.n=n;}// printNumber.accept(x) outputs "x", where x is an integer.publicvoidzero(IntConsumerprintNumber)throwsInterruptedException{for(inti=0;i<n;++i){z.acquire(1);printNumber.accept(0);if(i%2==0){o.release(1);}else{e.release(1);}}}publicvoideven(IntConsumerprintNumber)throwsInterruptedException{for(inti=2;i<=n;i+=2){e.acquire(1);printNumber.accept(i);z.release(1);}}publicvoidodd(IntConsumerprintNumber)throwsInterruptedException{for(inti=1;i<=n;i+=2){o.acquire(1);printNumber.accept(i);z.release(1);}}}
#include<semaphore.h>classZeroEvenOdd{private:intn;sem_tz,e,o;public:ZeroEvenOdd(intn){this->n=n;sem_init(&z,0,1);sem_init(&e,0,0);sem_init(&o,0,0);}// printNumber(x) outputs "x", where x is an integer.voidzero(function<void(int)>printNumber){for(inti=0;i<n;++i){sem_wait(&z);printNumber(0);if(i%2==0){sem_post(&o);}else{sem_post(&e);}}}voideven(function<void(int)>printNumber){for(inti=2;i<=n;i+=2){sem_wait(&e);printNumber(i);sem_post(&z);}}voidodd(function<void(int)>printNumber){for(inti=1;i<=n;i+=2){sem_wait(&o);printNumber(i);sem_post(&z);}}};