HCL Interview Question for Developer Program Engineers


Country: India




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

PsuedoCode:

initialization:
    // set semA to 1 so that the call to sem_wait in the
    // even thread will succeed right away
    sem_init(semA, 1)
    sem_init(semB, 0)

even_thread:
   to_print = 0;

   loop:
       sem_wait(semA);

       write(to_print);
       to_print += 2

       sem_post(semB)

odd_thread:
    to_print = 1

    loop:
        sem_wait(semB)

        write(to_print)
        to_print += 2

        sem_post(semA)

C Code:

pthread_mutex_t count_mutex     = PTHREAD_MUTEX_INITIALIZER;
    pthread_cond_t  condition_var   = PTHREAD_COND_INITIALIZER;

    void *functionCount1();
    void *functionCount2();

    int  count = 0;
    #define COUNT_DONE  200

    main()
    {
       pthread_t thread1, thread2;

       pthread_create( &thread1, NULL, &functionCount1, NULL);
       pthread_create( &thread2, NULL, &functionCount2, NULL);

       pthread_join( thread1, NULL);
       pthread_join( thread2, NULL);

       exit(0);
    }

    // Print odd numbers

    void *functionCount1()
    {
       for(;;)
       {

          // Lock mutex and then wait for signal to relase mutex
          pthread_mutex_lock( &count_mutex );


          // Check if the last emitted value was an odd; if so, wait till
          // an even is printed
          if (count % 2 != 0) {
              pthread_cond_wait( &condition_var, &count_mutex );
          }

          count++;
          printf("Counter value functionCount1: %d\n",count);
          pthread_cond_signal( &condition_var );

          if(count >= COUNT_DONE) {
             pthread_mutex_unlock( &count_mutex );
             return(NULL);
          }
          pthread_mutex_unlock( &count_mutex );
        }
    }


    // print even numbers
    void *functionCount2()
    {
       for(;;)
       {

          // Lock mutex and then wait for signal to relase mutex
          pthread_mutex_lock( &count_mutex );

          // Check if the last emitted value was an even; if so, wait till
          // an odd is printed
          if (count % 2 == 0) {
              pthread_cond_wait( &condition_var, &count_mutex );
          }

          count++;
          printf("Counter value functionCount2: %d\n",count);

          pthread_cond_signal( &condition_var );

          if(count >= COUNT_DONE) {
             pthread_mutex_unlock( &count_mutex );
             return(NULL);
          }
          pthread_mutex_unlock( &count_mutex );
        }
    }

    Output::
    ubuntu:~/work$ gcc even_odd.c -lpthread
    ubuntu:~/work$ ./a.out 
    Counter value functionCount1: 1
    Counter value functionCount2: 2
    Counter value functionCount1: 3
    Counter value functionCount2: 4
    Counter value functionCount1: 5
    Counter value functionCount2: 6
    Counter value functionCount1: 7
    Counter value functionCount2: 8
    Counter value functionCount1: 9
    Counter value functionCount2: 10

- R@M3$H.N January 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

//global variables

pthread_cond_t condA = PTHREAD_COND_INITIALIZER;
pthread_cond_t condB = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int totalNum = 0;

void *threadA()
{
while(totalNum <= 10)
{
/* Wait for totalNum to be even */
pthread_mutex_lock(&mutex);
while (totalNum % 2 != 0)
pthread_cond_wait(&condA, &mutex);
pthread_mutex_unlock(&mutex);

/* print and increment the number and wake up thread B */
pthread_mutex_lock(&mutex);
printf("A: %d\n", totalNum++);
pthread_cond_signal(&condB);
pthread_mutex_unlock(&mutex);

}

return 0;
}

void *threadB()
{


while(totalNum<=10)
{
/* Wait for totalNum to be odd */
pthread_mutex_lock(&mutex);
while (totalNum %2 == 0)
pthread_cond_wait(&condB, &mutex);
pthread_mutex_unlock(&mutex);



/* print and increment totalNum and wake up thread A */
pthread_mutex_lock(&mutex);
printf("B: %d\n", totalNum++);
pthread_cond_signal(&condA);
pthread_mutex_unlock(&mutex);
}

return 0;
}

- Yang January 12, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

//global variables

pthread_cond_t      condA  = PTHREAD_COND_INITIALIZER;
pthread_cond_t      condB  = PTHREAD_COND_INITIALIZER;
pthread_mutex_t     mutex = PTHREAD_MUTEX_INITIALIZER;
int totalNum = 0;

void *threadA()
{
    while(totalNum <= 10)
    {
        pthread_mutex_lock(&mutex);
        while (totalNum % 2 != 0)
            pthread_cond_wait(&condA, &mutex);
        pthread_mutex_unlock(&mutex);

        pthread_mutex_lock(&mutex);
        printf("A: %d\n", totalNum++);
        pthread_cond_signal(&condB);
        pthread_mutex_unlock(&mutex);

    }

    return 0;
}

void *threadB()
{

    while(totalNum<=10)
    {
        pthread_mutex_lock(&mutex);
        while (totalNum %2 == 0)
            pthread_cond_wait(&condB, &mutex);
        pthread_mutex_unlock(&mutex);


        pthread_mutex_lock(&mutex);
        printf("B: %d\n", totalNum++); 
        pthread_cond_signal(&condA);
        pthread_mutex_unlock(&mutex);
    }

    return 0;
}

- Yang January 12, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package prep.thread.implementations;

public class EvenOddThread {

public static void main(String[] args) {
Thread evenThread = new Thread(new EvenThread(), "EVEN-THREAD");
Thread oddThread = new Thread(new OddThread(), "ODD-THREAD");

evenThread.start();
oddThread.start();
}

}

class EvenThread implements Runnable {

@Override
public void run() {
int evenNum = 2;
while(true){
evenNum += 2;
System.out.println(Thread.currentThread().getName() + "---->" + evenNum);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (evenNum == 100) {
break;
}
}

}

}

class OddThread implements Runnable {

@Override
public void run() {
int oddNum = 1;
while(true){
oddNum += 2;
System.out.println(Thread.currentThread().getName() + "---->" + oddNum);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (oddNum == 101) {
break;
}
}

}

}

- Kashif January 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Basic old java solution

public class ThreadParityPrinterInterrupted {
   public static volatile int counter;

   public static void main(String[] args) throws Exception {
      Thread even = new Thread(new Even(), "Even");
      Thread odd = new Thread(new Odd(), "Odd");
      even.start();
      odd.start();
      while (true) {
         counter++;
         even.interrupt();
         odd.interrupt();
         Thread.sleep(1000L);
      }
   }

   private static class Even implements Runnable {
      @Override
      public void run() {
         int oldNum = 0;
         while (true) {
            try {
               Thread.sleep(Long.MAX_VALUE);
            } catch (InterruptedException e) {}
            int num = counter;
            if (num != oldNum && num % 2 == 0) {
               System.out.println(Thread.currentThread().getName() + " " + num);
               oldNum = num;
            }
         }
      }
   }

   private static class Odd implements Runnable {
      @Override
      public void run() {
         int oldNum = 0;
         while (true) {
            try {
               Thread.sleep(Long.MAX_VALUE);
            } catch (InterruptedException e) {}
            int num = counter;
            if (oldNum != num && num % 2 == 1) {
               System.out.println(Thread.currentThread().getName() + " " + num);
               oldNum = num;
            }
         }
      }
   }
}

- Andrew February 18, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Basic old java solution

public class ThreadParityPrinterInterrupted {
   public static volatile int counter;

   public static void main(String[] args) throws Exception {
      Thread even = new Thread(new Even(), "Even");
      Thread odd = new Thread(new Odd(), "Odd");
      even.start();
      odd.start();
      while (true) {
         counter++;
         even.interrupt();
         odd.interrupt();
         Thread.sleep(1000L);
      }
   }

   private static class Even implements Runnable {
      @Override
      public void run() {
         int oldNum = 0;
         while (true) {
            try {
               Thread.sleep(Long.MAX_VALUE);
            } catch (InterruptedException e) {}
            int num = counter;
            if (num != oldNum && num % 2 == 0) {
               System.out.println(Thread.currentThread().getName() + " " + num);
               oldNum = num;
            }
         }
      }
   }

   private static class Odd implements Runnable {
      @Override
      public void run() {
         int oldNum = 0;
         while (true) {
            try {
               Thread.sleep(Long.MAX_VALUE);
            } catch (InterruptedException e) {}
            int num = counter;
            if (oldNum != num && num % 2 == 1) {
               System.out.println(Thread.currentThread().getName() + " " + num);
               oldNum = num;
            }
         }
      }
   }
}

- Andrew February 18, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Code which counts till MAX_NUM for an arbitrary number of threads. Uses only binary mutex;

#include <iostream>
#include<stdio.h>
#include <pthread.h>
using namespace std;
// Initiliazer variables ///
const int MAX_NUM=12;
const int THREADS=3;
//////////////////////////
int gCount=0;
pthread_mutex_t mt;
void *print(void* ptr)
{
	int id = *((int*)(ptr));
	while(1)
	{
		if(gCount>MAX_NUM)
			break;
		pthread_mutex_lock (&mt);
		if(gCount<= MAX_NUM && gCount%THREADS == id)
		{
			cout<<"thread "<<id<<" - "<<gCount<<endl;
			gCount++;
		}
		pthread_mutex_unlock (&mt);
	}
	pthread_exit(NULL); 
}

int main()
{
	pthread_t T[THREADS];
	pthread_mutex_init(&mt, NULL);
	int i[THREADS];
	for(int j=0; j<THREADS; j++) 
	{
		i[j]=j;
		pthread_create(&T[j],NULL,print,&i[j]);
	}
	for(int j=0; j<THREADS; j++) 
		pthread_join(T[j],NULL);
	pthread_exit(NULL);
	return 0;
}

- NGT March 18, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include<stdio.h>
#include <pthread.h>
using namespace std;
// Initiliazer variables ///
const int MAX_NUM=12;
const int THREADS=3;
//////////////////////////
int gCount=0;
pthread_mutex_t mt;
void *print(void* ptr)
{
	int id = *((int*)(ptr));
	while(1)
	{
		if(gCount>MAX_NUM)
			break;
		pthread_mutex_lock (&mt);
		if(gCount<= MAX_NUM && gCount%THREADS == id)
		{
			cout<<"thread "<<id<<" - "<<gCount<<endl;
			gCount++;
		}
		pthread_mutex_unlock (&mt);
	}
	pthread_exit(NULL); 
}

int main()
{
	pthread_t T[THREADS];
	pthread_mutex_init(&mt, NULL);
	int i[THREADS];
	for(int j=0; j<THREADS; j++) 
	{
		i[j]=j;
		pthread_create(&T[j],NULL,print,&i[j]);
	}
	for(int j=0; j<THREADS; j++) 
		pthread_join(T[j],NULL);
	pthread_exit(NULL);
	return 0;
}

- NGT March 18, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include<stdio.h>
#include <pthread.h>
using namespace std;
// Initiliazer variables ///
const int MAX_NUM=12;
const int THREADS=3;
//////////////////////////
int gCount=0;
pthread_mutex_t mt;
void *print(void* ptr)
{
	int id = *((int*)(ptr));
	while(1)
	{
		if(gCount>MAX_NUM)
			break;
		pthread_mutex_lock (&mt);
		if(gCount<= MAX_NUM && gCount%THREADS == id)
		{
			cout<<"thread "<<id<<" - "<<gCount<<endl;
			gCount++;
		}
		pthread_mutex_unlock (&mt);
	}
	pthread_exit(NULL); 
}

int main()
{
	pthread_t T[THREADS];
	pthread_mutex_init(&mt, NULL);
	int i[THREADS];
	for(int j=0; j<THREADS; j++) 
	{
		i[j]=j;
		pthread_create(&T[j],NULL,print,&i[j]);
	}
	for(int j=0; j<THREADS; j++) 
		pthread_join(T[j],NULL);
	pthread_exit(NULL);
	return 0;
}

- NGT March 18, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

check

- NGT March 18, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Cpp Code for alternatively counting using arbitrary number of threads using a single binary mutex.

#include <iostream>
#include<stdio.h>
#include <pthread.h>
using namespace std;
// Initiliazer variables ///
const int MAX_NUM=12;
const int THREADS=3;
//////////////////////////
int gCount=0;
pthread_mutex_t mt;
void *print(void* ptr)
{
	int id = *((int*)(ptr));
	while(1)
	{
		if(gCount>MAX_NUM)
			break;
		pthread_mutex_lock (&mt);
		if(gCount<= MAX_NUM && gCount%THREADS == id)
		{
			cout<<"thread "<<id<<" - "<<gCount<<endl;
			gCount++;
		}
		pthread_mutex_unlock (&mt);
	}
	pthread_exit(NULL); 
}

int main()
{
	pthread_t T[THREADS];
	pthread_mutex_init(&mt, NULL);
	int i[THREADS];
	for(int j=0; j<THREADS; j++) 
	{
		i[j]=j;
		pthread_create(&T[j],NULL,print,&i[j]);
	}
	for(int j=0; j<THREADS; j++) 
		pthread_join(T[j],NULL);
	pthread_exit(NULL);
	return 0;
}

- NGT March 18, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package com.javafries.thread;

public class EvenOddNumberPrinter {

private static class NumberPrinter {

// To check if even number is printed or not.
private boolean isEvenPrinted = true;

public void printOdd(int number) throws InterruptedException {
// Get a lock on NumberPrinter
synchronized (this) {

// Wait until even is not printed.
if (!isEvenPrinted)
wait();

System.out.println(number);

isEvenPrinted = false;

// Notify the other waiting thread which is waiting on
// NumberPrinter
// Other thread will get out of waiting state
notify();
}
}

public void printEven(int number) throws InterruptedException {
synchronized (this) {
if (isEvenPrinted)
wait();

System.out.println(number);
isEvenPrinted = true;
notify();
}
}
}

private static class OddNumberGenerator implements Runnable {
private NumberPrinter q;
private int max;

public OddNumberGenerator(NumberPrinter q, int max) {
this.q = q;
this.max = max;
}

@Override
public void run() {
for (int i = 1; i < max; i = i + 2) {
try {
q.printOdd(i);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}

private static class EvenNumberGenerator implements Runnable {
private NumberPrinter printer;
private int max;

public EvenNumberGenerator(NumberPrinter printer, int max) {
this.printer = printer;
this.max = max;
}

@Override
public void run() {
for (int i = 2; i <= max; i = i + 2) {
try {
printer.printEven(i);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}

public static void main(String[] args) {
int maxNumber = 10;
NumberPrinter printer = new NumberPrinter();

new Thread(new EvenNumberGenerator(printer, maxNumber)).start();
new Thread(new OddNumberGenerator(printer, maxNumber)).start();
}
}

- Shanu April 12, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class EvenOddNumberPrinter {

	private static class NumberPrinter {

		// To check if even number is printed or not.
		private boolean isEvenPrinted = true;

		public void printOdd(int number) throws InterruptedException {
			// Get a lock on NumberPrinter
			synchronized (this) {

				// Wait until even is not printed.
				if (!isEvenPrinted)
					wait();

				System.out.println(number);

				isEvenPrinted = false;

				// Notify the other waiting thread which is waiting on
				// NumberPrinter
				// Other thread will get out of waiting state
				notify();
			}
		}

		public void printEven(int number) throws InterruptedException {
			synchronized (this) {
				if (isEvenPrinted)
					wait();

				System.out.println(number);
				isEvenPrinted = true;
				notify();
			}
		}
	}

	private static class OddNumberGenerator implements Runnable {
		private NumberPrinter q;
		private int max;

		public OddNumberGenerator(NumberPrinter q, int max) {
			this.q = q;
			this.max = max;
		}

		@Override
		public void run() {
			for (int i = 1; i < max; i = i + 2) {
				try {
					q.printOdd(i);
				} catch (InterruptedException ex) {
					ex.printStackTrace();
				}
			}
		}
	}

	private static class EvenNumberGenerator implements Runnable {
		private NumberPrinter printer;
		private int max;

		public EvenNumberGenerator(NumberPrinter printer, int max) {
			this.printer = printer;
			this.max = max;
		}

		@Override
		public void run() {
			for (int i = 2; i <= max; i = i + 2) {
				try {
					printer.printEven(i);
				} catch (InterruptedException ex) {
					ex.printStackTrace();
				}
			}
		}
	}

	public static void main(String[] args) {
		int maxNumber = 10;
		NumberPrinter printer = new NumberPrinter();

		new Thread(new EvenNumberGenerator(printer, maxNumber)).start();
		new Thread(new OddNumberGenerator(printer, maxNumber)).start();
	}
}

- Shanu April 12, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>
#include<pthread.h>

pthread_key_t keyN;
void* thfun(int* val){

pthread_t thid = pthread_self();
int n = (int*)*val;
printf("thid: %ld, number: %d\n", thid, n);
pthread_setspecific(keyN, &n);
while(n<20){
n = n+2;
pthread_setspecific(keyN, &n);
printf("thid: %ld, number: %d\n", thid, n);
}

return NULL;
}

int main(int argc, char* argv[]){

pthread_t thid1, thid2;
int x = 1;
int y = 2;

pthread_key_create(&keyN, NULL);
pthread_create(&thid1, NULL, &thfun, &x);
pthread_create(&thid1, NULL, &thfun, &y);

int res;
pthread_join(thid1, &res);
pthread_join(thid2, &res);
return 0;
}

}

- vikram May 12, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package com.basics.threads;

import java.util.Scanner;

public class EvenOdd implements Runnable {

	private static int count = 0;

	public static void main(String[] args) throws InterruptedException {

		Scanner sc = new Scanner(System.in);

		count = sc.nextInt();

		EvenOdd obj = new EvenOdd();
		Thread even = new Thread(obj, "Even");
		Thread odd = new Thread(obj, "Odd");
		
		even.start();
		even.join();
		
		odd.start();

	}

	@Override
	public void run() {

		String name = Thread.currentThread().getName();
		for (int i = 0; i <= count; i++) {
			if (name.equals("Even")) {
				if (i % 2 == 0)
					System.out.println(name + " - " + i);
			} else {
				if (i % 2 != 0)
					System.out.println(name + " - " + i);

			}

		}

	}
}

- Ish July 18, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package com.basics.threads;

import java.util.Scanner;

public class EvenOdd implements Runnable {

	private static int count = 0;

	public static void main(String[] args) throws InterruptedException {

		Scanner sc = new Scanner(System.in);

		count = sc.nextInt();

		EvenOdd obj = new EvenOdd();
		Thread even = new Thread(obj, "Even");
		Thread odd = new Thread(obj, "Odd");
		
		even.start();
		even.join();
		
		odd.start();

	}

	@Override
	public void run() {

		String name = Thread.currentThread().getName();
		for (int i = 0; i <= count; i++) {
			if (name.equals("Even")) {
				if (i % 2 == 0)
					System.out.println(name + " - " + i);
			} else {
				if (i % 2 != 0)
					System.out.println(name + " - " + i);

			}

		}

	}
}

- Ish July 18, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{
{
{


package com.basics.threads;

import java.util.Scanner;

public class EvenOdd implements Runnable {

private static int count = 0;

public static void main(String[] args) throws InterruptedException {

Scanner sc = new Scanner(System.in);

count = sc.nextInt();

EvenOdd obj = new EvenOdd();
Thread even = new Thread(obj, "Even");
Thread odd = new Thread(obj, "Odd");

even.start();
even.join();

odd.start();

}

@Override
public void run() {

String name = Thread.currentThread().getName();
for (int i = 0; i <= count; i++) {
if (name.equals("Even")) {
if (i % 2 == 0)
System.out.println(name + " - " + i);
} else {
if (i % 2 != 0)
System.out.println(name + " - " + i);

}

}

}
}



}
}
}

- Ish July 18, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

All java solutions are wrong here.

- javamaster January 27, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

using namespace std;
class Test {
thread t1, t2;
mutex m;
public:
Test() {
t1 = thread(&Test::printOdd, this);
t2 = thread(&Test::printEven, this);
t1.join();
t2.join();
}
void printOdd() {
int i = 1;
while (i < 20) {
m.lock();
cout << "From ODD thread "<< i << endl;
i = i + 2;
m.unlock();
}
}
void printEven(){
int i = 2;
while (i < 20) {
m.lock();
cout <<"From EVEN thread " <<i << endl;
i = i + 2;
m.unlock();
}
}

};
int main() {
Test t;

system("pause");
return 0;

}

- ankit March 06, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

using namespace std;
class Test {
	thread t1, t2;
	mutex m;
public:
	Test() {
		t1 = thread(&Test::printOdd, this);
		t2 = thread(&Test::printEven, this);
		t1.join();
		t2.join();
	}
	void printOdd() {
		int i = 1;
		while (i < 20) {
			m.lock();
			cout << "From ODD thread "<< i << endl;
			i = i + 2;
			m.unlock();
		}
	}
	void printEven(){
		int i = 2;
		while (i < 20) {
			m.lock();
			cout <<"From EVEN thread " <<i << endl;
			i = i + 2;
			m.unlock();
		}
	}
	
};
int main() {
	Test t;

	system("pause");
	return 0;

}

- ankit March 06, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class OddEvenPrint {

public static void main(String[] args) {
MyThread1 t1 = new MyThread1("ODD");
MyThread1 t2 = new MyThread1("EVEN");

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

}

}

class MyThread1 extends Thread {
int count;

MyThread1(String name) {
super(name);
}

public void run() {
for (int count = 1; count < 10; count++) {
//System.out.println(Thread.currentThread().getName());
try {
if (count % 2 == 0
&& Thread.currentThread().getName()
.equalsIgnoreCase("EVEN")) {
System.out.println(Thread.currentThread().getName()
+ " printed-- " + count);
} else if (count % 2 == 1
&& Thread.currentThread().getName()
.equalsIgnoreCase("ODD")) {
System.out.println(Thread.currentThread().getName()
+ " printed-- " + count);
}
Thread.sleep(3000);
} catch (InterruptedException e) {
}
}
}
}

- Abhra March 27, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class OddEvenPrint {

	public static void main(String[] args) {
		MyThread1 t1 = new MyThread1("ODD");
		MyThread1 t2 = new MyThread1("EVEN");

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

	}

}

class MyThread1 extends Thread {
	 int count;

	MyThread1(String name) {
		super(name);
	}

	public void run() {
		for (int count = 1; count < 10; count++) {
			//System.out.println(Thread.currentThread().getName());
			try {
				if (count % 2 == 0
						&& Thread.currentThread().getName()
								.equalsIgnoreCase("EVEN")) {
					System.out.println(Thread.currentThread().getName()
							+ " printed-- " + count);
				} else if (count % 2 == 1
						&& Thread.currentThread().getName()
								.equalsIgnoreCase("ODD")) {
					System.out.println(Thread.currentThread().getName()
							+ " printed-- " + count);
				}
				Thread.sleep(3000);
			} catch (InterruptedException e) {
			}
		}
	}
}

- Abhra March 27, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include "stdafx.h"
#include <thread>
#include <condition_variable>
#include <mutex>

long cntVal = 0;
std::condition_variable prntNum;
std::mutex pMutx;
#define MAXVAL 200

void printInt(bool onlyEven)
{

	for (;;)
	{
		if (cntVal >= MAXVAL)
		{
			break;
		}
		std::unique_lock<std::mutex> lk(pMutx);
		if (onlyEven == true)
		{
			if (cntVal % 2 != 0)
			{
				prntNum.wait(lk, [] { return cntVal % 2 == 0; });
			}
		}
		else
		{
			if (cntVal % 2 == 0)
			{
				prntNum.wait(lk, [] { return cntVal % 2 != 0; });
			}
		}
		printf("Count is %d\n", cntVal);
		cntVal++;
		prntNum.notify_one();
	}


}

int main()
{
	std::thread ev(printInt, true);
	std::thread odd(printInt, false);

	ev.join();
	odd.join();
    return 0;
}

- C-11 July 12, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

One way to solve this :

import java.util.concurrent.atomic.AtomicInteger;
public class EvenOddPrinter  {
    protected volatile static AtomicInteger count = new AtomicInteger(0);
    public volatile static boolean flag = false ;
    public static void main (String  [] args ) {
        new Thread ( () ->  {
               // while ( count.get() < 100 ) {
                  while (true ) {
                    if (!flag) {
                     System.out.print(count.getAndIncrement()+ " ") ;
                    }
                    flag = true;
                }
            } ).start();
        new Thread ( () ->  {
                //while ( count.get() < 100 ) {
                  while (true ) {
                    if (flag) {
                     System.out.print(count.getAndIncrement() + " ") ;
                     flag = true;
                    }
                    }
            } ).start();
    }
}

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

package com.oracle.threads;

import java.util.concurrent.locks.ReentrantLock;

public class ReentractLockExample {
    private int count =1;
    private volatile boolean oddEvenFlag = true;
    ReentrantLock lock = new ReentrantLock();
    public static void main(String args[]){

        ReentractLockExample rl = new ReentractLockExample();
        Thread t1 = new Thread(new PrintOddThread(rl));
        Thread t2 = new Thread(new PrintEvenThread(rl));
        t1.setName("OddThread");
        t2.setName("EvenThread");
        t1.start();
        t2.start();
    }

    static class PrintOddThread implements Runnable{

        ReentractLockExample r;
        PrintOddThread(ReentractLockExample r){
            this.r = r;
        }

        @Override
        public void run() {
            while(true){
                r.lock.lock();
                try {
                    if(r.oddEvenFlag == true) {
                        System.out.println(Thread.currentThread().getName() + ":" + r.lock.getHoldCount()+":" + r.count++);
                        Thread.sleep(1000);
                        r.oddEvenFlag = false;
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    r.lock.unlock();
                }

            }
        }
    }
    static class PrintEvenThread implements Runnable{

        ReentractLockExample r;
        PrintEvenThread(ReentractLockExample r){
            this.r = r;
        }

        @Override
        public void run() {
            while(true){
                r.lock.lock();
                try {
                    if(r.oddEvenFlag == false) {
                        System.out.println(Thread.currentThread().getName() + ":" + r.lock.getHoldCount()+":" + r.count++);
                        Thread.sleep(1000);
                        r.oddEvenFlag = true;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    r.lock.unlock();
                }

            }
        }
    }
}

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

package com.oracle.threads;

import java.util.concurrent.locks.ReentrantLock;

public class ReentractLockExample {
    private int count =1;
    private volatile boolean oddEvenFlag = true;
    ReentrantLock lock = new ReentrantLock();
    public static void main(String args[]){

        ReentractLockExample rl = new ReentractLockExample();
        Thread t1 = new Thread(new PrintOddThread(rl));
        Thread t2 = new Thread(new PrintEvenThread(rl));
        t1.setName("OddThread");
        t2.setName("EvenThread");
        t1.start();
        t2.start();
    }

    static class PrintOddThread implements Runnable{

        ReentractLockExample r;
        PrintOddThread(ReentractLockExample r){
            this.r = r;
        }

        @Override
        public void run() {
            while(true){
                r.lock.lock();
                try {
                    if(r.oddEvenFlag == true) {
                        System.out.println(Thread.currentThread().getName() + ":" + r.lock.getHoldCount()+":" + r.count++);
                        Thread.sleep(1000);
                        r.oddEvenFlag = false;
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    r.lock.unlock();
                }

            }
        }
    }
    static class PrintEvenThread implements Runnable{

        ReentractLockExample r;
        PrintEvenThread(ReentractLockExample r){
            this.r = r;
        }

        @Override
        public void run() {
            while(true){
                r.lock.lock();
                try {
                    if(r.oddEvenFlag == false) {
                        System.out.println(Thread.currentThread().getName() + ":" + r.lock.getHoldCount()+":" + r.count++);
                        Thread.sleep(1000);
                        r.oddEvenFlag = true;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    r.lock.unlock();
                }

            }
        }
    }
}

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

package com.oracle.threads;

import java.util.concurrent.locks.ReentrantLock;

public class ReentractLockExample {
    private int count =1;
    private volatile boolean oddEvenFlag = true;
    ReentrantLock lock = new ReentrantLock();
    public static void main(String args[]){

        ReentractLockExample rl = new ReentractLockExample();
        Thread t1 = new Thread(new PrintOddThread(rl));
        Thread t2 = new Thread(new PrintEvenThread(rl));
        t1.setName("OddThread");
        t2.setName("EvenThread");
        t1.start();
        t2.start();
    }

    static class PrintOddThread implements Runnable{

        ReentractLockExample r;
        PrintOddThread(ReentractLockExample r){
            this.r = r;
        }

        @Override
        public void run() {
            while(true){
                r.lock.lock();
                try {
                    if(r.oddEvenFlag == true) {
                        System.out.println(Thread.currentThread().getName() + ":" + r.lock.getHoldCount()+":" + r.count++);
                        Thread.sleep(1000);
                        r.oddEvenFlag = false;
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    r.lock.unlock();
                }

            }
        }
    }
    static class PrintEvenThread implements Runnable{

        ReentractLockExample r;
        PrintEvenThread(ReentractLockExample r){
            this.r = r;
        }

        @Override
        public void run() {
            while(true){
                r.lock.lock();
                try {
                    if(r.oddEvenFlag == false) {
                        System.out.println(Thread.currentThread().getName() + ":" + r.lock.getHoldCount()+":" + r.count++);
                        Thread.sleep(1000);
                        r.oddEvenFlag = true;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    r.lock.unlock();
                }

            }
        }
    }
}

- Using ReentrantLock August 23, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is another sample using C++ Threads

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

#define MAX 1000

int counter = 1;
std::condition_variable cv;
std::mutex mtx;

void PrintEven()
{
    std::unique_lock<std::mutex> lock(mtx);
    while (counter < MAX)
    {
        cv.wait(lock, [] { return !(counter & 1); });
        std::cout << counter << " ";
        counter++;
        cv.notify_one();
    }
}

void PrintOdd()
{
    std::unique_lock<std::mutex> lock(mtx);
    while (counter < MAX)
    {
        cv.wait(lock, [] { return (counter & 1); });
        std::cout << counter << " ";
        counter++;
        cv.notify_one();
    }
}

int main()
{
    std::thread even(PrintEven);
    std::thread odd(PrintOdd);

    even.join();
    odd.join();
}

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

Here is another implementation using C++ Threads

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

#define MAX 1000

int counter = 1;
std::condition_variable cv;
std::mutex mtx;

void PrintEven()
{
    std::unique_lock<std::mutex> lock(mtx);
    while (counter < MAX)
    {
        cv.wait(lock, [] { return !(counter & 1); });
        std::cout << counter << " ";
        counter++;
        cv.notify_one();
    }
}

void PrintOdd()
{
    std::unique_lock<std::mutex> lock(mtx);
    while (counter < MAX)
    {
        cv.wait(lock, [] { return (counter & 1); });
        std::cout << counter << " ";
        counter++;
        cv.notify_one();
    }
}

int main()
{
    std::thread even(PrintEven);
    std::thread odd(PrintOdd);

    even.join();
    odd.join();
}

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

Here is another implementation using C++ Threads

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

#define MAX 1000

int counter = 1;
std::condition_variable cv;
std::mutex mtx;

void PrintEven()
{
    std::unique_lock<std::mutex> lock(mtx);
    while (counter < MAX)
    {
        cv.wait(lock, [] { return !(counter & 1); });
        std::cout << counter << " ";
        counter++;
        cv.notify_one();
    }
}

void PrintOdd()
{
    std::unique_lock<std::mutex> lock(mtx);
    while (counter < MAX)
    {
        cv.wait(lock, [] { return (counter & 1); });
        std::cout << counter << " ";
        counter++;
        cv.notify_one();
    }
}

int main()
{
    std::thread even(PrintEven);
    std::thread odd(PrintOdd);

    even.join();
    odd.join();
}

- Anand December 07, 2018 | 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_even, cv_odd;
int current = 1; // Shared variable to determine the next number to print
const int MAX = 10; // Set the maximum value to be printed

void printEven() {
    while (current <= MAX) {
        std::unique_lock<std::mutex> lk(mtx);
        cv_even.wait(lk, [] { return current % 2 == 0; });
        if (current > MAX) break;
        std::cout << "Even Thread: " << current << std::endl;
        current++;
        cv_odd.notify_one(); // Notify odd thread to print next
    }
}

void printOdd() {
    while (current <= MAX) {
        std::unique_lock<std::mutex> lk(mtx);
        cv_odd.wait(lk, [] { return current % 2 != 0; });
        if (current > MAX) break;
        std::cout << "Odd Thread: " << current << std::endl;
        current++;
        cv_even.notify_one(); // Notify even thread to print next
    }
}

int main() {
    std::thread evenThread(printEven);
    std::thread oddThread(printOdd);

    evenThread.join();
    oddThread.join();

    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