Goldman Sachs Interview Question for SDE-2s


Country: United States
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
1
of 1 vote

public class One {
	static String name = "oneTwo";
	static int t = 1, limit = 6;
	static volatile boolean flag = true;

	static class MyThread extends Thread {
		Semaphore sem;
		String threadName;

		public MyThread(Semaphore sem, String threadName) {
			this.sem = sem;
			this.threadName = threadName;
		}

		public void run() {
			try {
				while (flag) {
					sem.acquire();
					if (t == 7)
						break;
					if (threadName.equalsIgnoreCase("one")
							&& threadName.equals(name.substring(0, 3))) {
						System.out.print(0);
						name = name.substring(3);

					} else if (threadName.equalsIgnoreCase("two")
							&& name.equalsIgnoreCase("two")) {
						System.out.print(t);
						t++;
						name = "oneThree";
					} else if (threadName.equalsIgnoreCase("three")
							&& name.equalsIgnoreCase("three")) {
						System.out.print(t);
						t++;
						name = "oneTwo";
					}
					sem.release();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}

	}
	public static void main(String[] args) {
		Semaphore sem = new Semaphore(1);
		MyThread one = new MyThread(sem, "one");
		MyThread two = new MyThread(sem, "two");
		MyThread three = new MyThread(sem, "three");
		one.start();
		two.start();
		three.start();
	}}

- Faisal September 11, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This is a super janky way to do it.

Why do you use strings at all? Using ints is much nicer (and faster).

Why is flag never used beyond a while loop? You should just do while(t <= limit). Also why is it volatile? It's not passed anywhere and there's not hardware that's going to wipe its specific address anyway.

- Anonymous December 06, 2018 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

package com.home.careercup;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*
Thread ordering. There are 4 threads ( instead of three required by the problem ).
First thread keeps printing 0
Second thread prints 1, 3, 5, ..
Third thread prints 0
Last thread will print 2,4,6,..
The synchronization will interleave the output to get the needed sequence
There is a Queue and condition variables to signal the queue condition.

First thread will act when queue size =0, drops a token into the queue.
Signals that queue size =1

Second thread waits till queue size =1 and then prints and then drops another token
into the queue. Signals to others that size = 2

Third thread waits till queue size =2 and then prints and then drops another token
into the queue. Signals to others that size = 3

Last thread waits till queue size =3 and then prints and then drops another token
into the queue. But size is now 4 and the queue is drained. Signals to others that
the queue size = 0. The first thread can now do its printing again.

Cycle continues .. ??

It should be trivial to implement something similar with 3 threads instead of 4.
 */
public class ThreadOrdering {

    public static void main(String[] args) throws Exception {
        Lock master = new ReentrantLock(true);
        Condition c0 = master.newCondition(); // queue size =0
        Condition c1 = master.newCondition();// queue size= 1
        Condition c2 = master.newCondition();// queue size =2
        Condition c3 = master.newCondition(); // queue size =3

        new Thread(new Printer(0, 0, 0, master, c0, c1)).start();
        new Thread(new Printer(1, 2, 1, master, c1, c2)).start();
        new Thread(new Printer(0, 0, 2, master, c2, c3)).start();
        new Thread(new Printer(2, 2, 3, master, c3, c0)).start();

        /*
        prints
        0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0 10 0 11 0 12 0 13 0 14 0 15 0
        16 0 17 0 18 0 19 0 20 0 21 0 22 0 23 0 24 0 25 0 26 0 27 0 28 0 29 0 30 0
        31 0 32 0 33 0 ..
         */

    }

    private static class Printer implements Runnable {
        int start;
        int inc;
        int current, size;
        Lock lock;
        Condition[] conditions;

        Printer(int start, int inc, int size, Lock lock, Condition... conditions) {
            this.start = start;
            this.inc = inc;
            current = start;
            this.lock = lock;
            Queue<Integer> q = Printer.q;
            this.size = size;
            this.conditions = conditions;
        }

        //shared across all printer threads
        static Deque<Integer> q = new LinkedList<>();

        @Override
        public void run() {
            while (true) {
                try {
                    lock.lock();
                    while (this.q.size() != size)
                        conditions[0].await();
                    synchronized (System.out) {
                        System.out.printf("%d ", current);
                        current += inc;
                    }
                    this.q.offer(1);
                    if (this.q.size() >= 4)
                        while (this.q.size() != 0)
                            this.q.remove();
                    conditions[1].signalAll();

                } catch (Exception e) {

                } finally {
                    lock.unlock();
                }

            }
        }


    }
}

- Makarand September 12, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

why synchronized is required for System.out?
Its already inside the lock

- mbhat2013 March 30, 2019 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

// Globals are terribly bad...
// use closure instead
$state = 0 
$even = true 

def exit(){ $state >= 12  }

def func_0(){  
    while( !exit() ){ 
      #atomic{
        if ( 2 /? $state ){
          printf(0)
          $state += 1
          $even = !$even
        }
     } 
  } 
}

def func_even(){ 
   n = 0 
    while( !exit() ){ 
      #atomic{
        if ( $state % 2 == 1 && $even ){
          n += 2 
          printf(n)
          $state += 1
        }
     } 
  } 
}

def func_odd(){ 
   n = -1 
    while( !exit() ){ 
      #atomic{
        if ( $state % 2 == 1 && !$even ){
          n += 2 
          printf(n)
          $state += 1
        }
     } 
  } 
}

threads = [ thread() as { func_0() } , thread() as { func_even() } , thread() as { func_odd() } ]
while ( exists( threads ) where { $.o.alive } );
println()

- NoOne September 04, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I tried using a shared variable in class to signel the threads.

package com.refresher.problems;

public class MultipleThreadsTogether {

    protected int threadSequence = 0;

    public static void main(String[] args) {
        MultipleThreadsTogether mtt = new MultipleThreadsTogether();
        mtt.printSequenceWithThreads();
    }

    public void printSequenceWithThreads() {

        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                try {
                    int i=1;
                    for(i=1; i<=10; ) {
                        if(threadSequence == 0) {
                            System.out.print(" " + 0);
                            if(i%2 == 0) {
                                threadSequence = 2;
                            } else {
                                threadSequence = 1;
                            }
                            i++;
                        }
                        Thread.sleep(100);
                    }
                } catch(InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        };


        Runnable r2 = new Runnable(){
            @Override
            public void run() {
                try {
                    int i = 1;
                    for (i = 1; i <= (10 * 2);) {
                        if(threadSequence == 1) {
                            System.out.print(" " + i);
                            threadSequence = 0;
                            i = i + 2;
                        }
                        Thread.sleep(100);
                    }
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        };

        Runnable r3 = new Runnable() {
            @Override
            public void run() {
                try {
                    int i = 2;
                    for (i = 2; i <= (10 * 2); ) {
                        if(threadSequence == 2) {
                            System.out.print(" " + i);
                            threadSequence = 0;
                            i = i + 2;
                        }
                        Thread.sleep(100);
                    }
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        };

        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);
        Thread t3 = new Thread(r3);

        t1.start();
        t2.start();
        t3.start();
    }

}

- Mahesh Kulkarni September 06, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

@Mahesh - I am not sure if the interviewer will be mighty pleased with this solution. I guess what they want three run () methods that behave between themselves using some synchronization mechanism ( and they should be able to go as fast as possible with no deadlocks). Using some kind of global state (as you did ) is also a solution - but surely not what they are looking for. Thanks

- Makarand September 08, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This is the solution I would come up with. Language C#.

internal class MultithreadedNumbers
    {
        private int CurrentPrint;
        private object Locker;
        private bool ReadyForZero;

        private enum NumberType
        {
            Odd, Even, Zero
        }

        internal MultithreadedNumbers()
        {
            CurrentPrint = 1;
            Locker = new object();
            ReadyForZero = true;
        }

        internal void Start(int max)
        {
            if(max < 1)
            {
                return;
            }

            Thread mod0 = new Thread(() => { ThreadMethod(max, NumberType.Zero); });
            Thread mod1 = new Thread(() => { ThreadMethod(max, NumberType.Odd); });
            Thread mod2 = new Thread(() => { ThreadMethod(max, NumberType.Even); });

            mod0.Start();
            mod1.Start();
            mod2.Start();

            // Determine if odd or even is called last and join that thread.
            if (max % 2 == 0)
            {
                mod2.Join();
            }
            else
            {
                mod1.Join();
            }
        }

        private void ThreadMethod(int max, NumberType numType)
        {
            while (Printing(max))
            {
                // Lock the locker to prevent race conditions.
                lock (Locker)
                {
                    switch (numType)
                    {
                        case NumberType.Zero:
                            if (Printing(max))
                            {
                                PrintZeros();
                            }
                            break;
                        case NumberType.Even:
                            PrintEvens();
                            break;
                        case NumberType.Odd:
                            PrintOdds();
                            break;
                    }
                }
            }
        }

        private bool Printing(int max)
        {
            return CurrentPrint <= max;
        }

        private void PrintZeros()
        {
            if (ReadyForZero)
            {
                Console.Write(0);
                ReadyForZero = false;
            }
        }

        private void PrintEvens()
        {
            if (CurrentPrint % 2 == 0 && !ReadyForZero)
            {
                PrintNumber();
            }
        }

        private void PrintOdds()
        {
            if (CurrentPrint % 2 != 0 && !ReadyForZero)
            {
                PrintNumber();
            }
        }

        private void PrintNumber()
        {
            Console.Write(CurrentPrint);
            ReadyForZero = true;
            CurrentPrint++;
        }
    }

- Anthony September 10, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package goldmansach;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PrintThreadSeries {

	public static class Counter {
		int count = 1;
		boolean even = false;

		public void increment() {
			try {
				wait();

				System.out.println(count);
				count++;

			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			even = true;
			notifyAll();
		}
	}

	Counter counter = new Counter();
	
	static int count = 1;
	static Lock lock = new ReentrantLock();
	public static class MyThread extends Thread {
		String name = "one";
		public boolean zero = true;
		public boolean even = false;

	

		@Override
		public void run() {
			while (count < 7) {
				lock.lock();
				if (this.name.equals("one") && zero ) {
					System.out.println(0);
					zero = false;
					
					this.name= !even ? "two" : "three";
				} else if (this.name.equals("two")) {
					System.out.println(count);
					count++;
					zero = true;
					even = true;
					this.name ="one";
				} else if(this.name.equals("three")){
					System.out.println(count);
					count++;
					even = false;
					zero = true;
					this.name ="one";
				}
				lock.unlock();
			}
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		PrintThreadSeries.Counter c = new PrintThreadSeries.Counter();
		MyThread t1 = new MyThread();
		MyThread t2 = new MyThread();
		MyThread t3 = new MyThread();
		t1.start();
		t2.start();
		t3.start();
	}

}

- Siddhi October 01, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package goldmansach;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PrintThreadSeries {

	public static class Counter {
		int count = 1;
		boolean even = false;

		public void increment() {
			try {
				wait();

				System.out.println(count);
				count++;

			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			even = true;
			notifyAll();
		}
	}

	Counter counter = new Counter();
	
	static int count = 1;
	static Lock lock = new ReentrantLock();
	public static class MyThread extends Thread {
		String name = "one";
		public boolean zero = true;
		public boolean even = false;

	

		@Override
		public void run() {
			while (count < 7) {
				lock.lock();
				if (this.name.equals("one") && zero ) {
					System.out.println(0);
					zero = false;
					
					this.name= !even ? "two" : "three";
				} else if (this.name.equals("two")) {
					System.out.println(count);
					count++;
					zero = true;
					even = true;
					this.name ="one";
				} else if(this.name.equals("three")){
					System.out.println(count);
					count++;
					even = false;
					zero = true;
					this.name ="one";
				}
				lock.unlock();
			}
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		PrintThreadSeries.Counter c = new PrintThreadSeries.Counter();
		MyThread t1 = new MyThread();
		MyThread t2 = new MyThread();
		MyThread t3 = new MyThread();
		t1.start();
		t2.start();
		t3.start();
	}

}

- Siddhi October 01, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class PrintSeries0102030405 {

public static void main(String[] args) throws Exception {
Print0 print0 = new Print0();
PrintEven even = new PrintEven(print0);
Thread thread1 = new Thread(print0);
Thread thread2 = new Thread(even);
thread1.start();
Thread.sleep(200);
thread2.start();
}

}

class Print0 implements Runnable {

@Override
public void run() {

synchronized (this) {
int even = 2;
while (even < 20) {
System.out.print(0);
try {
this.wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
even += 2;
}

}

}

}

class PrintEven implements Runnable {
Print0 print0;

PrintEven(Print0 print0) {
this.print0 = print0;
}

@Override
public void run() {
synchronized (print0) {
int even = 2;
while (even < 20) {
System.out.print(even);
try {
print0.wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
even += 2;
}
}
}

}

- Pk October 08, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class PrintSeries0102030405 {

public static void main(String[] args) throws Exception {
Print0 print0 = new Print0();
PrintEven even = new PrintEven(print0);
PrintOdd odd = new PrintOdd(print0);
Thread thread1 = new Thread(print0);
Thread thread2 = new Thread(even);
Thread thread3 = new Thread(odd);
thread1.start();
Thread.sleep(200);
thread3.start();
Thread.sleep(200);
thread2.start();
}

}

class Print0 implements Runnable {

@Override
public void run() {

synchronized (this) {
int even = 2;
while (even < 20) {
System.out.print(0);
try {
this.wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
even += 2;
}

}

}

}

class PrintOdd implements Runnable {
Print0 print0;

PrintOdd(Print0 print0) {
this.print0 = print0;
}

@Override
public void run() {
synchronized (print0) {
int odd = 1;
while (odd < 20) {
System.out.print(odd);
try {
print0.wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
odd += 2;
}
}
}

}

class PrintEven implements Runnable {
Print0 print0;

PrintEven(Print0 print0) {
this.print0 = print0;
}

@Override
public void run() {
synchronized (print0) {
int even = 2;
while (even < 20) {
System.out.print(even);
try {
print0.wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
even += 2;
}
}
}

}

- Pk October 08, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Below is the Simple C++11 solution

#include<iostream>
#include<thread>
#include<pthread.h>
using namespace std;

pthread_mutex_t lock;
int turn = 1;

void trythis(int id)
{
    static int count = 1;
    bool flag = true;
    while(flag) {
        pthread_mutex_lock(&lock);
        if(count == 7) {
            break;
            flag = false;
        }
        if(turn == 1) {
            if(id == 1) {
                cout<<"0";
                turn = (count % 2) == 0 ? 2 : 3;
            }
        } else if (turn == 2) {
            if(id == 2) {
                cout<<count;
                count++;
                turn = 1;
            }
        } else if( turn == 3) {
            if(id == 2) {
                cout<<count;
                count++;
                turn = 1;
            }
        }
        pthread_mutex_unlock(&lock);
    }
    return;
}

int main(void)
{
    int i = 0;
    int rc;
    int error;
    thread t1(trythis, 1);
    thread t2(trythis, 2);
    thread t3(trythis, 3);
    t1.join();
    t2.join();
    t3.join();
    return 0;
}

- DEEPAKKUSHWAH2302 October 08, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

pseudo code

semaphore sem1=1,sem2=0,sem3=0,sem4=0;

count =0;

thread1{

while(1){

wait (sem1);
print("0");
signal (sem3);

wait(sem2);
print(0);
signal(sem4);
}
}

thread2{
wait(sem3);
print(count++);
signal(sem2);
}

thread3{
wait(sem4);
print(count++);
signal(sem1);
}

- personal.dummy2016 October 12, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Test010203 {
public static void main(String[] args) {
Object monitor = new Object();
Task task = new Task(monitor);

Thread t1=new Thread(task,"T1");
Thread t2=new Thread(task,"T2");
Thread t3=new Thread(task,"T3");

t1.start();
t2.start();
t3.start();

}
}

class Task implements Runnable {

private Object monitor = new Object();

private boolean firstTask=true;
private boolean secTask=false;
private boolean thridTask=false;

int count=1;
int i=0;


public Task(Object monitor){
this.monitor=monitor;
}

public void run(){
try {
while (true) {
synchronized (monitor) {
String tName = Thread.currentThread().getName();
if (firstTask && tName.equalsIgnoreCase("T1")) {
System.out.println(tName + ":" + "0");
if(i++ % 2 ==0) {
thridTask=true;
} else {
secTask=true;
}
firstTask=false;
monitor.notifyAll();
monitor.wait();
} else if (secTask && tName.equalsIgnoreCase("T2")) {
System.out.println(tName + ":" + i);
secTask=false;
firstTask=true;
monitor.notifyAll();
monitor.wait();
} else if (thridTask && tName.equalsIgnoreCase("T3")) {
System.out.println(tName + ":" + i);
thridTask=false;
firstTask=true;
monitor.notifyAll();
monitor.wait();
} else {
monitor.wait();
}
}
Thread.sleep(1000);
}
} catch (InterruptedException ie){
System.out.println("Thread interrupted ");
ie.printStackTrace();
} catch (Exception e) {
System.out.println("Other exception");
e.printStackTrace();
}
}

}

- Hemanth October 28, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class solution {

    static int state = 0;
    static int counter = 1;
    static volatile boolean runState = true;

    class ZeroOddEvenThreadLock implements Runnable {
        private String name;
        private Integer total;
        private ReentrantLock Lock;

        public ZeroOddEvenThreadLock(String name, Integer total, ReentrantLock Lock){
            this.name = name;
            this.total = total;
            this.Lock = Lock;
        }

        public void run(){
            while(runState) {
                if (counter > total) {
                    runState = false;
                    break;
                } else if ((state == 0 || state == 2) && name.equals("zero") ||
                        state == 1 && name.equals("odd") ||
                        state == 3 && name.equals("even")) {
                    Lock.lock();
                    try {
                        System.out.print((name.equals("zero") ? 0 : counter++));
                        state = (state + 1) % 4;
                    } finally {
                        Lock.unlock();
                    }
                }
            }
        }
    }

    public void ThreadQ1lock(){
	
        ExecutorService executor = Executors.newFixedThreadPool(3);
        ReentrantLock Lock = new ReentrantLock();

        int total = 6;

        Runnable zero = new ZeroOddEvenThreadLock("zero", total, Lock);
        Runnable odd = new ZeroOddEvenThreadLock("odd", total, Lock);
        Runnable even = new ZeroOddEvenThreadLock("even", total, Lock);

        executor.submit(zero);
        executor.submit(odd);
        executor.submit(even);

        stop(executor);
        System.out.println();
    }

    public static void main(String args[]){
        solution app = new solution();
        app.ThreadQ1lock();
    }
}

- dhruv November 02, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

wrong - above solution is not multithreaded rather just a loop.

- kartikeya April 05, 2019 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Animation extends Thread {

static int a = 0;
static int odd = 1;
static int even = 2;
static int limit = 6;
static boolean x = false;

synchronized static void print() {

if (a == 0) {
System.out.print(a++);
if (x == false) {
a = 1;
} else {
a = 2;
}
} else if (a == 1) {
System.out.print(odd);
odd += 2;
a = 0;
x = true;
} else if (a == 2) {
System.out.print(even);
even += 2;
a = 0;
x = false;
}

}

public static void main(String[] args) {
Thread x = new Thread(new Thread() {
public void run() {
print();

}
});
Thread z = new Thread(new Thread() {

public void run() {
print();
}

});
while (true) {
if (odd == limit + 1) {
break;
}
print();
}
Animation l = new Animation();
l.start();
x.start();
z.start();

}

- Bahaa Samoudi November 25, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            OddEven.PrintOddEven();
            Console.ReadKey();
        }
    }

    public class OddEven
    {
        static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1, 1);
        static Thread Odd;
        static Thread Even;
        static Thread Zero;
        static LinkedList<int> Numbers = new LinkedList<int>();

        private static void PrintOdd()
        {
            while (Numbers.Count > 0)
            {
                semaphoreSlim.Wait();
                var a = Numbers.FirstOrDefault();
                if (a % 2 != 0)
                {
                    Console.WriteLine(a);
                    Numbers.RemoveFirst();
                }
                semaphoreSlim.Release();
            }
        }
        private static void PrintEven()
        {
            while (Numbers.Count > 0)
            {
                semaphoreSlim.Wait();
                var a = Numbers.FirstOrDefault();
                if (a % 2 == 0)
                {
                    Console.WriteLine(a);
                    Numbers.RemoveFirst();
                }
                semaphoreSlim.Release();
            }
        }

        private static void PrintZero()
        {
            while (Numbers.Count > 1)
            {
                semaphoreSlim.Wait();
                var a = Numbers.FirstOrDefault();
                if (a == 0)
                {
                    Console.WriteLine(a);
                    Numbers.RemoveFirst();
                }
                semaphoreSlim.Release();
            }
        }

        public static void PrintOddEven()
        {
            for (int i = 1; i <= 10; i++)
            {
                Numbers.AddLast(0);
                Numbers.AddLast(i);
            }

            Zero = new Thread(PrintZero);
            Odd = new Thread(PrintOdd);
            Even = new Thread(PrintEven);

            Zero.Name = "Zero";
            Odd.Name = "Odd";
            Even.Name = "Even";
            Zero.Start();
            Odd.Start();
            Even.Start();
            Odd.Join();
            Even.Join();
        }
    }
}

- GUL MD ERSHAD November 28, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package problem.threading;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Print series 010203040506. Using multi-threading 1st thread will print only 0
 * 2nd thread will print only even numbers and 3rd thread print only odd
 * numbers.
 * 
 * @author ramsharma
 *
 */
public class ThreadSynch {

	private int st = 0;
	private static boolean flag;
	private final Object lock = new Object();
	private final CyclicBarrier cb = new CyclicBarrier(3);

	public static void main(String[] args) {
		ThreadSynch ths = new ThreadSynch();
		Thread printZero = new Thread(new ZeroThread(ths));
		Thread printOdd = new Thread(new OddThread(ths));
		Thread printEven = new Thread(new EvenThread(ths));

		// printZero.start();
		// printOdd.start();
		// printEven.start();

		ExecutorService exc = Executors.newFixedThreadPool(3);
		exc.submit(printZero);
		exc.submit(printOdd);
		exc.submit(printEven);

		exc.shutdown();
	}

	static class OddThread implements Runnable {

		private final ThreadSynch cb;

		public OddThread(ThreadSynch ths) {
			this.cb = ths;
		}

		@Override
		public void run() {
			for (int i = 1; i < 10; i = i + 2) {

				synchronized (cb) {

					while (cb.st != 1) {
						try {
							cb.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}

					if (cb.st == 1) {
						System.out.print(i);
						// i += 2;
					}
					cb.st = 0;
					cb.notifyAll();
				}
				// cb.await();
			}
		}
	}

	static class EvenThread implements Runnable {

		private final ThreadSynch cb;

		public EvenThread(ThreadSynch ths) {
			this.cb = ths;
		}

		@Override
		public void run() {

			for (int i = 2; i < 10; i = i + 2) {

				synchronized (cb) {

					while (cb.st != 2) {
						try {
							cb.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}

					if (cb.st == 2) {
						System.out.print(i);
						// i += 2;
					}
					cb.st = 0;
					cb.notifyAll();
				}
				// cb.await();
			}
		}
	}

	static class ZeroThread implements Runnable {

		private final ThreadSynch cb;

		public ZeroThread(ThreadSynch ths) {
			this.cb = ths;

		}

		@Override
		public void run() {
			for (int i = 0; i < 10; i++) {

				synchronized (cb) {
					while (cb.st != 0) {
						try {
							cb.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}

					if (cb.st == 0) {
						System.out.print("0");
					}
					if (flag) {
						cb.st = 2;
						flag = false;
					}
					else {
						cb.st = 1;
						flag = true;
					}
					cb.notifyAll();
				}
			}
		}
	}
}

- shramdc November 29, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class MyThread implements Runnable {

    int num, in, orig;
    Object lock;
    static int turn = 0;

    MyThread(int num, int in, Object lock) {
        this.orig = num;
        this.num = num;
        this.in = in;
        this.lock = lock;
    }

    public void run() {
        synchronized (lock) {
            for (int i = 0; i < (orig==0?10:5); i++) {
                while (checkTurn() != orig) {
                    try {
                        lock.wait();
                    } catch (InterruptedException ex) {
                        System.out.println(ex.getMessage());
                    }
                }
                System.out.println(Thread.currentThread().getName() + " " + num);
                num += in;
                turn++;
                lock.notifyAll();
            }
        }
    }
    
    private int checkTurn() {
        if(turn%2!=0)
        {
            if(((turn+1)/2)%2==0)
                return 2;
            else
                return 1;
        }
        return 0;
    }

    public static void main(String[] args) {
        Object lock = new Object();
        Thread t1 = new Thread(new MyThread(0, 0, lock));
        Thread t3 = new Thread(new MyThread(1, 2, lock));
        Thread t2 = new Thread(new MyThread(2, 2, lock));

        t1.start();
        t3.start();
        t2.start();
    }
}

- Parth Shah December 12, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/*
Print series 010203040506. Using multi-threading 1st thread will print only 0
2nd thread will print only even numbers and 3rd thread print only odd numbers.
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>

int pos=0;
int count=1;
pthread_t tid[3];
pthread_mutex_t lock[3];

void* printEven(void *arg)
{
    pthread_mutex_lock(&lock[2]);
    pthread_mutex_lock(&lock[0]);
    while(pos < 12)
    {
        if((pos + 1)%4 == 0){
            printf("even %d\n", count);
            count++;
            pos++;
        }
        else
        {
           pthread_mutex_unlock(&lock[2]);
           pthread_mutex_unlock(&lock[0]);
        }
    }

    return NULL;

}
void* printOdd(void *arg)
{
    pthread_mutex_lock(&lock[1]);
    pthread_mutex_lock(&lock[2]);
    while(pos < 12)
    {
        if((pos - 1)%4 == 0){
            printf("Odd %d\n", count);
            count++;
            pos++;
        }
        else
        {
           pthread_mutex_unlock(&lock[1]);
           pthread_mutex_unlock(&lock[2]);
        }
    }

    return NULL;
}
void* printZero(void *arg)
{
    pthread_mutex_lock(&lock[0]);
    pthread_mutex_lock(&lock[1]);
    while(pos < 12)
    {
        if (pos%2 == 0){
            printf("Zero 0\n");
            pos++;
        }
        else
        {
           pthread_mutex_unlock(&lock[0]);
           pthread_mutex_unlock(&lock[1]);
        }
    }

    return NULL;

}
int main()
{
    int i;
    for(i=0;i<3;i++){
        if(pthread_mutex_init(&lock[i], NULL) != 0)
        {
            printf("Mutex creation failed\n");
            return 1;
        }
    }
    if( pthread_create(&tid[0], NULL, &printZero, NULL) !=0)
    {
        printf("Thread Creation failed!");
        return 1;
    }
    if(pthread_create(&tid[1], NULL, &printEven, NULL) !=0)
    {
        printf("Thread Creation failed!");
        return 1;
    }
    if(pthread_create(&tid[1], NULL, &printOdd, NULL) !=0)
    {
        printf("Thread Creation failed!");
        return 1;
    }
    for(i=0;i<3;i++)
        pthread_join(tid[i], NULL);
    for(i=0;i<3;i++)
        pthread_mutex_destroy(&lock[i]);

    return 0;
}

- RENJUASHOKAN January 07, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int[] arr = { 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6 };

Thread t0 = new Thread(p => Console.WriteLine($"Thread {Thread.CurrentThread.Name}: {string.Join(',', arr.Where(q => q == 0))}"));
t0.Name = "Zeros Thread";
t0.Start();

Thread tOdd = new Thread(p => Console.WriteLine($"Thread {Thread.CurrentThread.Name}: {string.Join(',', arr.Where(q => q % 2 != 0))}"));
tOdd.Name = "Odd Thread";
tOdd.Start();

Thread tEven = new Thread(p => Console.WriteLine($"Thread {Thread.CurrentThread.Name}: {string.Join(',', arr.Where(q => q % 2 == 0))}"));
tEven.Name = "Even Thread";
tEven.Start();

- BK February 11, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int[] arr = { 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6 };

            Thread t0 = new Thread(p => Console.WriteLine($"Thread {Thread.CurrentThread.Name}: {string.Join(',', arr.Where(q => q == 0))}"));
            t0.Name = "Zeros Thread";
            t0.Start();

            Thread tOdd = new Thread(p => Console.WriteLine($"Thread {Thread.CurrentThread.Name}: {string.Join(',', arr.Where(q => q % 2 != 0))}"));
            tOdd.Name = "Odd Thread";
            tOdd.Start();

            Thread tEven = new Thread(p => Console.WriteLine($"Thread {Thread.CurrentThread.Name}: {string.Join(',', arr.Where(q => q % 2 == 0))}"));
            tEven.Name = "Even Thread";
            tEven.Start();

- BK February 11, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package javaStuff;

/**
 * Monitor based solution to alternate between 3 threads 
 * to print the sequence :  0 1 2 0 3 4 0 5 6..
 * 
 */
public class AlternateThreadDemo {
	public static void main(String[] args) {
		Monitor monitor = new Monitor(0); //start with thread-0's turn
		
		Thread t1 = new Thread(new MyJob(0, 0, monitor));
		Thread t2 = new Thread(new MyJob(1, 1, monitor));
		Thread t3 = new Thread(new MyJob(2, 2, monitor));
		
		t1.start();
		t2.start();
		t3.start();
	}
}

/**
 * Communicates which thread to run next. 
 * turn/prevTurn together determine this.
 *  
 * @author ayemmanu
 */
class Monitor{
	int turn;
	int prevTurn;
	public Monitor(int id){	this.turn = id;	}
}

class MyJob implements Runnable{
	Monitor monitor;
	int id;
	int val;
	
	public MyJob(int id, int val, Monitor monitor){
		this.id = id;
		this.val = val;
		this.monitor = monitor;
	}
	
	@Override
	public void run() {
		while(true){
			synchronized(monitor){
				
				while(monitor.turn != this.id) //Wait for my thread turn
					try {	monitor.wait();	} 
					catch (InterruptedException e) {}
				
				System.out.print(val + " ");
				
				if(val != 0) val += 2; //Value to be printed in next turn of this thread.
				
				//Logic to switch between threads - 0 1 0 2 0 1 0 2 ..
				//if cur is 0th thread: Next go to 2 if last visited=1. else go to 1 if last visited=2;
				//else: Next switch to 0'th thread if cur thread = 1 or 2
				if (monitor.turn == 0) { 
					if (monitor.prevTurn == 1)	monitor.turn = 2;
					else					monitor.turn = 1;
				} else { 
					monitor.prevTurn = monitor.turn;
					monitor.turn = 0;
				}
				
				try {	Thread.sleep(10);	} catch (InterruptedException e) {}
				
				monitor.notifyAll(); //Awake everyone
			}
		}
	}
}

- X February 12, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <stdio.h>
#include <iostream>
#include <thread>
#include <mutex>

using namespace std;

mutex m1;
int i = 1;
bool even = false;
int turn = 0;

void print(int id){
	while (i < 7){
		m1.lock();
		if (id == 0 && turn == 0){
			cout << id << " - " << 0 << endl;
			if (i % 2 == 0){
				turn = 2;
			}
			else{
				turn = 1;
			}
		}
		else if (id == 1 && turn == 1){
				cout << id << " - " << i++ << endl;
				turn = 0;
		}
		else if (id == 2 && turn == 2){
			cout << id << " - " << i++ << endl;
			turn = 0;
		}
		m1.unlock();
	}
}

void main()
{
	thread Zero(print,0);
	thread Even(print,1);
	thread Odd(print,2);
	while (1);
}

- Anonymous September 30, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package com.multiThreading.career_Cup;


/**
 * goldman-sachs-interview-questions
 *
 * Print series 010203040506. Using multi-threading 1st thread will
 * print only 0 2nd thread will print only even numbers and 3rd thread print only odd numbers.
 */
public class PrintSeries01020304 {
  public static void main(String[] args) throws InterruptedException {
    PrintNum printNum =  new PrintNum();

    Thread zero = new Zero(printNum);
    zero.start();

    Thread odd = new Odd(printNum);
    odd.start();

    Thread even = new Even(printNum);
    even.start();
  }
}

class PrintNum{
  private  int i = 1;
  private int max = 20;
  private Boolean stateZero = true;
  private Boolean stateOdd = true;
  private Boolean stateEven = false;

  synchronized void printZero() throws InterruptedException {
    while (i<max){
      if (stateZero){
        System.out.println(0);
        stateZero = false;
        if(i % 2 == 0){
          stateEven = true;
        }
        else {
          stateOdd = true;
        }
        i++;
        notify();
      }
      wait();
    }
  }

  synchronized void printOdd() throws InterruptedException {
    while (i<max){
      if(stateOdd){
        System.out.println(i);
        stateZero = true;
        notify();
      }
      wait();
    }
  }

  synchronized void printEven() throws InterruptedException {
    while (i<max){
      if(stateEven){
        System.out.println(i);
        stateZero = true;
        notify();
      }
      wait();
    }
  }
}

class Zero extends Thread{
  private final PrintNum printNum;
  Zero(PrintNum printNum){
    this.printNum = printNum;
  }

  @Override
  public void run() {
    try {
      printNum.printZero();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}


class Odd  extends Thread{
  private final PrintNum printNum;
  Odd(PrintNum printNum){
    this.printNum = printNum;
  }

  @Override
  public void run() {
    try {
      printNum.printOdd();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}


class Even  extends Thread{
  private final PrintNum printNum;
  Even(PrintNum printNum){
    this.printNum = printNum;
  }

  @Override
  public void run() {
    try {
      printNum.printEven();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}

- Paras agarwal October 26, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class EvenOddZero {

	public static void main(String[] args) {

		EvenOddZero_Res res = new EvenOddZero_Res();
		Thread t1 = new Thread(new EvenOddZero_ZeroThread(res));
		Thread t2 = new Thread(new EvenOddZero_EvenThread(res));
		Thread t3 = new Thread(new EvenOddZero_OddThread(res));
		t1.start();
		t2.start();
		t3.start();
	}

}

class EvenOddZero_Res {
	boolean isZeroNow = true;
	int nextNumber = 1;
	
	public boolean isNextNumberIsEven() {
		return nextNumber%2 == 0;
	}
}

class EvenOddZero_EvenThread implements Runnable {
	EvenOddZero_Res res;

	public EvenOddZero_EvenThread(EvenOddZero_Res res) {
		this.res = res;
	}

	public void run() {
		while (true) {
			synchronized (res) {
				while (!res.isNextNumberIsEven() || res.isZeroNow) {
					try {
						res.wait();
					} catch (Exception e) {
					}
				}
				System.out.println("Even = " + res.nextNumber);
				res.nextNumber = res.nextNumber + 1;
				res.isZeroNow = true;
				res.notifyAll();
			}
		}
	}
}

class EvenOddZero_OddThread implements Runnable {
	EvenOddZero_Res res;

	public EvenOddZero_OddThread(EvenOddZero_Res res) {
		this.res = res;
	}

	public void run() {
		while (true) {
			synchronized (res) {
				while (res.isNextNumberIsEven() || res.isZeroNow) {
					try {
						res.wait();
					} catch (Exception e) {
					}
				}
				System.out.println("Odd = " + res.nextNumber);
				res.nextNumber = res.nextNumber + 1;
				res.isZeroNow = true;
				res.notifyAll();

			}
		}
	}
}

class EvenOddZero_ZeroThread implements Runnable {
	EvenOddZero_Res res;

	public EvenOddZero_ZeroThread(EvenOddZero_Res res) {
		this.res = res;
	}

	public void run() {
		while (true) {
			synchronized (res) {
				while (!res.isZeroNow) {
					try {
						res.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				System.out.println("Zero = " + 0);
				res.isZeroNow = false;
				res.notifyAll();
				if (res.nextNumber > 100) {
					System.exit(0);
				}
			}
		}
	}
}

- Rajat April 21, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class EvenOddZero {

	public static void main(String[] args) {

		EvenOddZero_Res res = new EvenOddZero_Res();
		Thread t1 = new Thread(new EvenOddZero_ZeroThread(res));
		Thread t2 = new Thread(new EvenOddZero_EvenThread(res));
		Thread t3 = new Thread(new EvenOddZero_OddThread(res));
		t1.start();
		t2.start();
		t3.start();
	}

}

class EvenOddZero_Res {
	boolean isZeroNow = true;
	int nextNumber = 1;
	
	public boolean isNextNumberIsEven() {
		return nextNumber%2 == 0;
	}
}

class EvenOddZero_EvenThread implements Runnable {
	EvenOddZero_Res res;

	public EvenOddZero_EvenThread(EvenOddZero_Res res) {
		this.res = res;
	}

	public void run() {
		while (true) {
			synchronized (res) {
				while (!res.isNextNumberIsEven() || res.isZeroNow) {
					try {
						res.wait();
					} catch (Exception e) {
					}
				}
				System.out.println("Even = " + res.nextNumber);
				res.nextNumber = res.nextNumber + 1;
				res.isZeroNow = true;
				res.notifyAll();
			}
		}
	}
}

class EvenOddZero_OddThread implements Runnable {
	EvenOddZero_Res res;

	public EvenOddZero_OddThread(EvenOddZero_Res res) {
		this.res = res;
	}

	public void run() {
		while (true) {
			synchronized (res) {
				while (res.isNextNumberIsEven() || res.isZeroNow) {
					try {
						res.wait();
					} catch (Exception e) {
					}
				}
				System.out.println("Odd = " + res.nextNumber);
				res.nextNumber = res.nextNumber + 1;
				res.isZeroNow = true;
				res.notifyAll();

			}
		}
	}
}

class EvenOddZero_ZeroThread implements Runnable {
	EvenOddZero_Res res;

	public EvenOddZero_ZeroThread(EvenOddZero_Res res) {
		this.res = res;
	}

	public void run() {
		while (true) {
			synchronized (res) {
				while (!res.isZeroNow) {
					try {
						res.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				System.out.println("Zero = " + 0);
				res.isZeroNow = false;
				res.notifyAll();
				if (res.nextNumber > 100) {
					System.exit(0);
				}
			}
		}
	}
}

- Rajat April 21, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

My Java Code:

public class ZeroOddEven {

	public static void main(String[] args) {
		NumberPrinter printer = new NumberPrinter();
		Thread t1 = new Thread(new CustomThread(Number.ZERO, printer));
		Thread t2 = new Thread(new CustomThread(Number.ODD, printer));
		Thread t3 = new Thread(new CustomThread(Number.EVEN, printer));
		t1.start();t2.start();t3.start();
	}
}

enum Number {
	ODD,
	EVEN,
	ZERO;
}

class CustomThread implements Runnable {
	
	Number numberType;
	NumberPrinter printer;
	
	CustomThread(Number numberType, NumberPrinter printer) {
		this.numberType = numberType;
		this.printer = printer;
	}
	
	private CustomThread() {}
	
	@Override
	public void run() {
		if (numberType == Number.ZERO) {
			for (int i = 0; i < 6; i++)
				printer.printZero();		
		}
		else if (numberType == Number.EVEN) {
			for (int i = 2; i <= 6; i = i + 2)
				printer.printEven(i);		
		}
		else if (numberType == Number.ODD) {
			for (int i = 1; i <= 5; i = i + 2)
				printer.printOdd(i);		
		}				
	}
}

class NumberPrinter {
	
	Number currentType = Number.ZERO;
	boolean nextEven;
	
	synchronized void printEven(int num) {
		while (currentType != Number.EVEN) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.print(num);
		currentType = Number.ZERO;
		nextEven = false;
		notifyAll();
	}
	
	synchronized void printOdd(int num) {
		while (currentType != Number.ODD) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.print(num);
		currentType = Number.ZERO;
		nextEven = true;
		notifyAll();
	}
	
	synchronized void printZero() {
		while (currentType != Number.ZERO) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.print("0");
		if (nextEven)
			currentType = Number.EVEN;
		else
			currentType = Number.ODD;
		notifyAll();
	}
}

- Rishav Jayswal June 16, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Java solution:

package com.ll;

public class ZeroOddEven {

	public static void main(String[] args) {
		NumberPrinter printer = new NumberPrinter();
		Thread t1 = new Thread(new CustomThread(Number.ZERO, printer));
		Thread t2 = new Thread(new CustomThread(Number.ODD, printer));
		Thread t3 = new Thread(new CustomThread(Number.EVEN, printer));
		t1.start();t2.start();t3.start();
	}
}

enum Number {
	ODD,
	EVEN,
	ZERO;
}

class CustomThread implements Runnable {
	
	Number numberType;
	NumberPrinter printer;
	
	CustomThread(Number numberType, NumberPrinter printer) {
		this.numberType = numberType;
		this.printer = printer;
	}
	
	private CustomThread() {}
	
	@Override
	public void run() {
		if (numberType == Number.ZERO) {
			for (int i = 0; i < 6; i++)
				printer.printZero();		
		}
		else if (numberType == Number.EVEN) {
			for (int i = 2; i <= 6; i = i + 2)
				printer.printEven(i);		
		}
		else if (numberType == Number.ODD) {
			for (int i = 1; i <= 5; i = i + 2)
				printer.printOdd(i);		
		}				
	}
}

class NumberPrinter {
	
	Number currentType = Number.ZERO;
	boolean nextEven;
	
	synchronized void printEven(int num) {
		while (currentType != Number.EVEN) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.print(num);
		currentType = Number.ZERO;
		nextEven = false;
		notifyAll();
	}
	
	synchronized void printOdd(int num) {
		while (currentType != Number.ODD) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.print(num);
		currentType = Number.ZERO;
		nextEven = true;
		notifyAll();
	}
	
	synchronized void printZero() {
		while (currentType != Number.ZERO) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.print("0");
		if (nextEven)
			currentType = Number.EVEN;
		else
			currentType = Number.ODD;
		notifyAll();
	}
}

- Rishav Jayswal June 16, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import threading
import pdb


class Var:

def __init__(self):
self.data = "odd"
self.even = 1
self.odd = 0

class Th(threading.Thread):


def __init__(self, condition, str1, Var):

threading.Thread.__init__(self)
self.condition = condition
self.strtype = str1
self.varobj = Var

if str1 == "even":
self.num = 2
else:
self.num = 3


def run(self ):

tmp = 0

while tmp <= 10:

#pdb.set_trace()
self.condition.acquire()

if self.strtype == "zero":

if self.varobj.data == "zero":
self.condition.wait()

if self.varobj.data == "even":
#self.condition.wait()
print " 0 ",
self.varobj.data = "zero"
self.condition.notifyAll()


if self.varobj.data == "odd":
#print "--------------------------------------------\n"
print " 0 ",
self.varobj.data = "zero"
self.condition.notifyAll()
#self.condition.release()

if self.strtype == "even":

if self.varobj.data == "zero" and self.varobj.even - self.varobj.odd == 1:
#print "--------------------------------------------\n"
print " "+str(self.num)+" ",
self.varobj.data = "even"
self.num = self.num + 2
self.varobj.even = self.varobj.even + 1
self.condition.notifyAll()
#self.condition.release()

if self.varobj.data == "even":
self.condition.wait()

if self.varobj.data == "odd":
self.condition.wait()


if self.strtype == "odd":

if self.varobj.data == "even":
self.condition.wait()

if self.varobj.data == "zero" and self.varobj.even - self.varobj.odd == 2:
#print "--------------------------------------------\n"
print " "+str(self.num)+" ",
self.num = self.num + 2
self.varobj.data = "odd"
self.varobj.odd = self.varobj.odd + 1
self.condition.notifyAll()
#self.condition.release()

if self.varobj.data == "odd":
self.condition.wait()


tmp = tmp + 1
self.condition.release()





def main():

con = threading.Condition()
t1 = Th(con, "zero")
t1.start()
t1.join()

if __name__ == '__main__':


#main()
v = Var()
con = threading.Condition()

t1 = Th(con, "zero", v)
t2 = Th(con, "even", v)
t3 = Th(con, "odd", v)

t2.start()
t3.start()
t1.start()

t1.join()
t2.join()
t3.join()

- Anonymous September 13, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import threading 
import pdb


class Var:

	def __init__(self):
		self.data = "odd"
		self.even = 1
		self.odd = 0

class Th(threading.Thread):


	def __init__(self, condition, str1, Var):

		threading.Thread.__init__(self)
		self.condition = condition
		self.strtype = str1
		self.varobj = Var
		
		if str1 == "even":
			self.num = 2
		else:
			self.num = 3


	def run(self ):

		tmp = 0

		while tmp <= 10:

			#pdb.set_trace()
			self.condition.acquire()

			if self.strtype == "zero":
				
				if self.varobj.data == "zero":
					self.condition.wait()

				if self.varobj.data == "even":
					#self.condition.wait()
					print " 0 ",
					self.varobj.data = "zero"
					self.condition.notifyAll()


				if self.varobj.data == "odd":
					#print "--------------------------------------------\n"
					print " 0 ",
					self.varobj.data = "zero"
					self.condition.notifyAll()
					#self.condition.release()

			if self.strtype == "even":

				if self.varobj.data == "zero" and self.varobj.even - self.varobj.odd  == 1:
					#print "--------------------------------------------\n"
					print " "+str(self.num)+" ",
					self.varobj.data = "even"
					self.num = self.num + 2
					self.varobj.even = self.varobj.even + 1
					self.condition.notifyAll()	
					#self.condition.release()				

				if self.varobj.data == "even":
					self.condition.wait()

				if self.varobj.data == "odd":
					self.condition.wait()


			if self.strtype == "odd":

				if self.varobj.data == "even":
					self.condition.wait()

				if self.varobj.data == "zero" and self.varobj.even - self.varobj.odd == 2:
					#print "--------------------------------------------\n"
					print " "+str(self.num)+" ",
					self.num = self.num + 2
					self.varobj.data = "odd"
					self.varobj.odd = self.varobj.odd + 1
					self.condition.notifyAll()
					#self.condition.release()

				if self.varobj.data == "odd":
					self.condition.wait()	

			
			tmp = tmp + 1
			self.condition.release()

			



def main():

	con = threading.Condition()
	t1 = Th(con, "zero")
	t1.start()
	t1.join()

if __name__ == '__main__':


	#main()
	v = Var()
	con = threading.Condition()

	t1 = Th(con, "zero", v)
	t2 = Th(con, "even", v)
	t3 = Th(con, "odd", v)

	t2.start()
	t3.start()
	t1.start()

	t1.join()
	t2.join()
	t3.join()

- Gopal Pawar September 13, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import threading 
import pdb


class Var:

	def __init__(self):
		self.data = "odd"
		self.even = 1
		self.odd = 0

class Th(threading.Thread):


	def __init__(self, condition, str1, Var):

		threading.Thread.__init__(self)
		self.condition = condition
		self.strtype = str1
		self.varobj = Var
		
		if str1 == "even":
			self.num = 2
		else:
			self.num = 3


	def run(self ):

		tmp = 0

		while tmp <= 10:

			#pdb.set_trace()
			self.condition.acquire()

			if self.strtype == "zero":
				
				if self.varobj.data == "zero":
					self.condition.wait()

				if self.varobj.data == "even":
					#self.condition.wait()
					print " 0 ",
					self.varobj.data = "zero"
					self.condition.notifyAll()


				if self.varobj.data == "odd":
					#print "--------------------------------------------\n"
					print " 0 ",
					self.varobj.data = "zero"
					self.condition.notifyAll()
					#self.condition.release()

			if self.strtype == "even":

				if self.varobj.data == "zero" and self.varobj.even - self.varobj.odd  == 1:
					#print "--------------------------------------------\n"
					print " "+str(self.num)+" ",
					self.varobj.data = "even"
					self.num = self.num + 2
					self.varobj.even = self.varobj.even + 1
					self.condition.notifyAll()	
					#self.condition.release()				

				if self.varobj.data == "even":
					self.condition.wait()

				if self.varobj.data == "odd":
					self.condition.wait()


			if self.strtype == "odd":

				if self.varobj.data == "even":
					self.condition.wait()

				if self.varobj.data == "zero" and self.varobj.even - self.varobj.odd == 2:
					#print "--------------------------------------------\n"
					print " "+str(self.num)+" ",
					self.num = self.num + 2
					self.varobj.data = "odd"
					self.varobj.odd = self.varobj.odd + 1
					self.condition.notifyAll()
					#self.condition.release()

				if self.varobj.data == "odd":
					self.condition.wait()	

			
			tmp = tmp + 1
			self.condition.release()

			



def main():

	con = threading.Condition()
	t1 = Th(con, "zero")
	t1.start()
	t1.join()

if __name__ == '__main__':


	#main()
	v = Var()
	con = threading.Condition()

	t1 = Th(con, "zero", v)
	t2 = Th(con, "even", v)
	t3 = Th(con, "odd", v)

	t2.start()
	t3.start()
	t1.start()

	t1.join()
	t2.join()
	t3.join()

- Gopal Pawar September 13, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <thread>
#include <mutex>
#include <unistd.h>
#include <vector>
#include <semaphore.h>


using namespace std;

sem_t sm1;
sem_t sm2;
sem_t sm3;
mutex mt;
int val1=0;
int val2=0;
int val3=0;

int g_num=0;


void print_number(int id)
{
while(1)
{
switch(id){
case 1:
{
sem_wait(&sm1);
mt.lock();
if (g_num >=500)
{
mt.unlock();
return;
}
std::cout <<"-->"<<0<<std::flush;
mt.unlock();
sem_post(&sm2);
}
break;
case 2:
sem_wait(&sm2);
mt.lock();
if (g_num >=500)
{
mt.unlock();
return;
}
++g_num;
std::cout <<"-->"<<g_num<<std::flush;
mt.unlock();
sem_post(&sm1);
break;

default:
cout <<"invalid id thread"<<endl;
}
}
}

void signal_thread()
{
mt.lock();
cout <<"sending signal to zero thread"<<endl;
sem_post(&sm1);
mt.unlock();
}


int main()
{
sem_init(&sm1, 0, val1);
sem_init(&sm2, 0, val2);
std::vector<thread> th_pool;
int i;
for ( i = 1; i <= 2; i++)
{
cout <<"thread id" <<i<<" created"<<endl;
th_pool.push_back(thread(print_number, i));
// sleep(1);
}
th_pool.push_back(thread(signal_thread));
cout <<"all thread created ..sending signal"<<endl;
//sem_post(&sm);

cout <<"waiting thread to join"<<endl;
for ( i = 0; i<th_pool.size(); i++)
th_pool[i].join();
cout<<endl;
return 0;
}

- Manoj saha September 29, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <thread>
#include<mutex>
#include<condition_variable>
using namespace std;
int inc = 0;
int isZero = 0;
mutex mu;
condition_variable cond1;
bool first = false;
void printO()
{

	while (inc < 100)
	{
		std::unique_lock<std::mutex> locker(mu);
		cond1.wait(locker, []() { return isZero == 0; });
		cout << " 0 ";
		if(first == false)
			++inc;
		first = true;
		isZero = 1;
		locker.unlock();	
		cond1.notify_all();
	}
}
void printOdd()
{
	while (inc < 100)
	{
		std::unique_lock<std::mutex> locker(mu);
		cond1.wait(locker, []() { return (isZero != 0 && inc > 0 && inc % 2 == 1); });
			cout << " " << inc << " ";
		++inc;
		isZero = 0;
		locker.unlock();		
		cond1.notify_all();
	}
}
void printEven()
{
	while (inc < 100)
	{
		std::unique_lock<std::mutex> locker(mu);
		cond1.wait(locker, []() { return (isZero != 0 && inc > 0 && inc % 2 == 0); });
		cout << " " << inc << " ";
		++inc;
		isZero = 0;
		locker.unlock();
		cond1.notify_all();
	}
}
int main()
{    
	std::thread t1(printEven);
	std::thread t2(printOdd);
	std::thread t3(printO);
	t1.join();
	t2.join();
	t3.join();

}

- deepesh December 04, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <thread>
#include<mutex>
#include<condition_variable>
using namespace std;
int inc = 0;
int isZero = 0;
mutex mu;
condition_variable cond1;
bool first = false;
void printO()
{

	while (inc < 100)
	{
		std::unique_lock<std::mutex> locker(mu);
		cond1.wait(locker, []() { return isZero == 0; });
		cout << " 0 ";
		if(first == false)
			++inc;
		first = true;
		isZero = 1;
		locker.unlock();	
		cond1.notify_all();
	}
}
void printOdd()
{
	while (inc < 100)
	{
		std::unique_lock<std::mutex> locker(mu);
		cond1.wait(locker, []() { return (isZero != 0 && inc > 0 && inc % 2 == 1); });
			cout << " " << inc << " ";
		++inc;
		isZero = 0;
		locker.unlock();		
		cond1.notify_all();
	}
}
void printEven()
{
	while (inc < 100)
	{
		std::unique_lock<std::mutex> locker(mu);
		cond1.wait(locker, []() { return (isZero != 0 && inc > 0 && inc % 2 == 0); });
		cout << " " << inc << " ";
		++inc;
		isZero = 0;
		locker.unlock();
		cond1.notify_all();
	}
}
int main()
{    
	std::thread t1(printEven);
	std::thread t2(printOdd);
	std::thread t3(printO);
	t1.join();
	t2.join();
	t3.join();

}

- deepesh December 04, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

from threading import Lock, Thread
zero_lock = Lock()
even_lock = Lock()
odd_lock = Lock()
# 010203040506

def zero_print():
odd = True
for n in range(6):
zero_lock.acquire()
print(0)
if odd:
odd = False
odd_lock.release()
else:
odd = True
even_lock.release()

def print_odd():
n = 1
while(n<=5):
odd_lock.acquire()
print(n)
n=n+2
zero_lock.release()

def print_even():
n = 2
while(n<=6):
even_lock.acquire()
print(n)
n=n+2
zero_lock.release()

t1 = Thread(target=zero_print)
t2 = Thread(target=print_odd)
t3 = Thread(target=print_even)
odd_lock.acquire()
even_lock.acquire()
threads = [t1,t2,t3]
for t in threads:
t.start()
for t in threads:
t.join()

- rahulroshan96 May 07, 2021 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

from threading import Lock, Thread
zero_lock = Lock()
even_lock = Lock()
odd_lock = Lock()
# 010203040506

def zero_print():
    odd = True
    for n in range(6):
        zero_lock.acquire()    
        print(0)
        if odd:
            odd = False
            odd_lock.release()
        else:
            odd = True
            even_lock.release()

def print_odd():
    n = 1
    while(n<=5):
        odd_lock.acquire()
        print(n)
        n=n+2
        zero_lock.release()
        
def print_even():
    n = 2
    while(n<=6):
        even_lock.acquire()
        print(n)
        n=n+2
        zero_lock.release()
        
t1 = Thread(target=zero_print)
t2 = Thread(target=print_odd)
t3 = Thread(target=print_even)
odd_lock.acquire()
even_lock.acquire()
threads = [t1,t2,t3]
for t in threads:
    t.start()
for t in threads:
    t.join()

- rahulroshan96 May 07, 2021 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex mtx;
std::condition_variable cv;
int current = 1; // Start with 1 to print '0' first
const int MAX = 6; // Maximum value to print
bool zeroTurn = true; // Control flag to alternate between zero and number printing

void printZero() {
while (true) {
std::unique_lock<std::mutex> lk(mtx);
cv.wait(lk, [] { return zeroTurn || current > MAX; });
if (current > MAX) {
break;
}
std::cout << 0;
zeroTurn = false; // Hand over the turn to print numbers
cv.notify_all();
}
}

void printEven() {
for (int i = 2; i <= MAX; i += 2) {
std::unique_lock<std::mutex> lk(mtx);
cv.wait(lk, [i] { return !zeroTurn && current == i; });
if (current > MAX) {
break;
}
std::cout << i;
++current;
zeroTurn = true; // Give turn back to zero
cv.notify_all();
}
}

void printOdd() {
for (int i = 1; i <= MAX; i += 2) {
std::unique_lock<std::mutex> lk(mtx);
cv.wait(lk, [i] { return !zeroTurn && current == i; });
if (current > MAX) {
break;
}
std::cout << i;
++current;
zeroTurn = true; // Give turn back to zero
cv.notify_all();
}
}

int main() {
std::thread threads[3];
threads[0] = std::thread(printZero);
threads[1] = std::thread(printEven);
threads[2] = std::thread(printOdd);

for (auto& t : threads) {
t.join();
}

std::cout << std::endl;
return 0;
}

- gera March 28, 2024 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex mtx;
std::condition_variable cv;
int current = 0; // Shared variable to determine the next number to print
const int MAX = 6; // Set the maximum value to be printed

void printZero() {
while (true) {
std::unique_lockstd::mutex lk(mtx);
cv.wait(lk, [] { return current % 2 == 0 || current > MAX; });
if (current > MAX) break;
std::cout << "0";
current++;
lk.unlock();
cv.notify_all();
}
}

void printEven() {
for (int i = 2; i <= MAX; i += 2) {
std::unique_lockstd::mutex lk(mtx);
cv.wait(lk, [i] { return current == i || current > MAX; });
if (current > MAX) break;
std::cout << i;
current++;
lk.unlock();
cv.notify_all();
}
}

void printOdd() {
for (int i = 1; i <= MAX; i += 2) {
std::unique_lockstd::mutex lk(mtx);
cv.wait(lk, [i] { return current == i || current > MAX; });
if (current > MAX) break;
std::cout << i;
current++;
lk.unlock();
cv.notify_all();
}
}

int main() {
std::thread threads[3];
threads[0] = std::thread(printZero);
threads[1] = std::thread(printEven);
threads[2] = std::thread(printOdd);
// Join threads with the main thread
for (auto& t : threads) {
t.join();
}

std::cout << std::endl;
return 0;
}

- gera March 28, 2024 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex mtx;
std::condition_variable cv;
int current = 0; // Shared variable to determine the next number to print
const int MAX = 6; // Set the maximum value to be printed

void printZero() {
while (true) {
std::unique_lockstd::mutex lk(mtx);
cv.wait(lk, [] { return current % 2 == 0 || current > MAX; });
if (current > MAX) break;
std::cout << "0";
current++;
lk.unlock();
cv.notify_all();
}
}

void printEven() {
for (int i = 2; i <= MAX; i += 2) {
std::unique_lockstd::mutex lk(mtx);
cv.wait(lk, [i] { return current == i || current > MAX; });
if (current > MAX) break;
std::cout << i;
current++;
lk.unlock();
cv.notify_all();
}
}

void printOdd() {
for (int i = 1; i <= MAX; i += 2) {
std::unique_lockstd::mutex lk(mtx);
cv.wait(lk, [i] { return current == i || current > MAX; });
if (current > MAX) break;
std::cout << i;
current++;
lk.unlock();
cv.notify_all();
}
}

int main() {
std::thread threads[3];
threads[0] = std::thread(printZero);
threads[1] = std::thread(printEven);
threads[2] = std::thread(printOdd);
// Join threads with the main thread
for (auto& t : threads) {
t.join();
}

std::cout << std::endl;
return 0;
}

- igvedmak March 28, 2024 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More