HCL Interview Question
Developer Program EngineersCountry: India
//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;
}
//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;
}
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;
}
}
}
}
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;
}
}
}
}
}
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;
}
}
}
}
}
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;
}
#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;
}
#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;
}
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;
}
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();
}
}
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();
}
}
#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;
}
}
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);
}
}
}
}
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);
}
}
}
}
{
{
{
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);
}
}
}
}
}
}
}
#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;
}
#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;
}
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) {
}
}
}
}
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) {
}
}
}
}
#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;
}
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();
}
}
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();
}
}
}
}
}
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();
}
}
}
}
}
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();
}
}
}
}
}
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();
}
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();
}
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();
}
PsuedoCode:
C Code:
- R@M3$H.N January 14, 2016