Novell Interview Question
Tech LeadsCountry: India
Interview Type: Phone Interview
Using Semaphore class:-
public class PrintList {
private List<Integer> list1 = Arrays.asList(new Integer[]{1,2,3,4,5});
private List<Integer> list2 = Arrays.asList(new Integer[]{1,2,3,4,5});
private List<Integer> list3 = Arrays.asList(new Integer[]{1,2,3,4,5});
private int listSize = 5;
private Semaphore semaphore = null;
public PrintList() {
semaphore = new Semaphore(3);
}
public void print() throws InterruptedException{
semaphore.acquire();
for(int i = 0;i<listSize;i++){
System.out.println(list1.get(i));
System.out.println(list2.get(i));
System.out.println(list3.get(i));
}
semaphore.release();
}
public static void main(String[] args) {
final PrintList printList = new PrintList();
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
printList.print();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Thread t1 = new Thread(runnable);
Thread t2 = new Thread(runnable);
Thread t3 = new Thread(runnable);
t1.start();t2.start();t3.start();
}
}
MasterThread t1 = new MasterThread(l1,t,1);
MasterThread t2 = new MasterThread(l2,t,2);
MasterThread t3 = new MasterThread(l3,t,3);
t1.start();
t2.start();
t3.start();
class MasterThread extends Thread{
private List<Integer> l;
private ThreeLists t;
private int threadNumber;
private static Map<Integer, Integer> _typesMap =
new HashMap<Integer, Integer>() {
{
put(1,2);
put(2,3);
put(3,1);
}
};
public MasterThread(List<Integer> list, ThreeLists tIN,int threadNumber) {
l = list;
t = tIN;
this.threadNumber = threadNumber;
}
public void run() {
int i = 0;
while (i < l.size()) {
synchronized (t) {
if (t.getI() != threadNumber)
{
try {
t.wait();
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println(l.get(i++));
t.setI(_typesMap.get(threadNumber));
t.notifyAll();
}
}
}
}
}
This may not work as per asked in question [1st thread 1 will print 1st element, then 2nd thread will print 1st and then 3rd will 1st element] There might be the chance 1st thread1 print and then thread3 print 1st element and then thread2 print the 1st element. Because once waiting thread get notify() any thread can run. I guess here you have to use Reentrant lock [java.util.concurrent.locks.ReentrantLock] which provides fair locking.
I am thinking of something like this,
Use a Same Integer Object and intialize to 1...
Then Join T1 to T2 to T3.....
Each Thread prints the numbers in this case 1 1 1.....
All the threads gets executed and then we
increment the Integer by 1....and this is in a loop for N times.....N being the numbe rof times we want to print the number.
package threads;
public class TwoThreadsSync
{
static int counter1 =0, counter2 =0,counter3 =0;
static int arry[] = {1,2,3,4,5};
static char chArry[] = {'a','b','c','d','e'};
static String strArry[] = {"one","two","three","four","five"};
private static int turn =1;
private static class First extends Thread
{
public void run()
{
while(counter1 <=4)
{
if(turn == 1)
{
System.out.println("First Thread: "+arry[counter1]);
counter1 += 1;
turn=2;
}
}
}
}
private static class Second extends Thread
{
public void run()
{
while(counter2 <=4)
{
if(turn == 2)
{
System.out.println("Second Thread: "+chArry[counter2]);
counter2 += 1;
turn=3;
}
}
}
}
private static class Third extends Thread
{
public void run()
{
while(counter3 <=4)
{
if(turn == 3)
{
System.out.println("Third Thread: "+strArry[counter3]);
counter3 += 1;
turn=1;
}
}
}
}
public static void main(String []args)
{
First f1 = new First();
Second s1 = new Second();
Third t1 = new Third();
f1.start();
s1.start();
t1.start();
}
}
class A
{
List<int> ints1 = new List<int>() { 1, 2, 3, 4 };
List<int> ints2 = new List<int>() { 5, 6, 7, 8 };
List<int> ints3 = new List<int>() { 9, 10, 11, 12 };
int syncObj1 = 0;
int syncObj2 = 0;
int syncObj3 = 1;
public void Print1()
{
foreach (int x in ints1)
{
while (syncObj3 != 1)
{
}
Console.WriteLine(x);
syncObj1 = 1;
syncObj2 = 0;
syncObj3 = 0;
while (syncObj2 != 1)
{
}
}
}
public void Print2()
{
foreach (int x in ints2)
{
while (syncObj1 != 1)
{
}
Console.WriteLine(x);
syncObj2 = 1;
syncObj1 = 0;
syncObj3 = 0;
while (syncObj3 != 1)
{
}
}
}
public void Print3()
{
foreach (int x in ints3)
{
while (syncObj2 != 1)
{
}
Console.WriteLine(x);
syncObj3 = 1;
syncObj1 = 0;
syncObj2 = 0;
while (syncObj1 != 1)
{
}
}
}
}
Hav you executed the code?, i think it will not wrk.If you dont call print2() from print1() and print3() from print2()..... It will not work sequentially.
If you have code with wait and notify, can you please post it. When i tried , the 1st thread itself is going into infinite wait.
Here is the complete code. I have executed the code and it works as expected.
class Program
{
static void Main(string[] args)
{
try
{
A a = new A();
//a.Initialize();
Thread t1 = new Thread(new ThreadStart(a.Print1));
Thread t2 = new Thread(new ThreadStart(a.Print2));
Thread t3 = new Thread(new ThreadStart(a.Print3));
t1.Start();
t2.Start();
t3.Start();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.Read();
}
}
there is no need of threading actually.
for(i=0;i<n;i++)
{
cout<<arr1[i] <<arr2[i] <<arr3[i];
}
let me correct me if i m :)
think this would work well for three integer array:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *a,*b,*c,len,i,j;
printf("enter the length of array:\n");
scanf("%d",&len);
a=(int *)calloc(len,sizeof(int));
if(a==NULL){printf("memory error:");return 0;}
b=(int *)calloc(len,sizeof(int));
if(b==NULL){printf("memory error:");return 0;}
c=(int *)calloc(len,sizeof(int));
if(c==NULL){printf("memory error:");return 0;}
printf("enter the array1 elements:\n");
for(i=0;i<len;i++)
scanf("%d",&a[i]);
printf("enter the array2 elements:\n");
for(i=0;i<len;i++)
scanf("%d",&b[i]);
printf("enter the array3 elements:\n");
for(i=0;i<len;i++)
scanf("%d",&c[i]);
for(i=0;i<len;i++)
printf("%d %d %d\n",a[i],b[i],c[i]);
return 0;
}
This could be achieved with a simple mutex and an array to keep track of the status. below is the complete code
/*Say there are 3 array lists l1, l2 & l3 of same length. Thress threads accessing three lists. Say T1 -> l1, T2 ->l2 & T3 ->l3. It should print in the order say first element of 1st then first element of 2nd list and then first element of 3rd list. Then second element of 1st then second element of 2nd list and then second element of 3rd list. */
#include<iostream>
#include <pthread.h>
#include <vector>
using namespace std;
#define NUM_THREADS 3
vector< vector<int> > g_vector(NUM_THREADS);
vector<bool> g_stat(NUM_THREADS, false);
int next_id = 0;
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
int
find_next_id(int cur_id) {
int cur = cur_id;
cur_id = (cur_id+1)%NUM_THREADS;
while(cur != cur_id) {
if(g_stat[cur_id] == false) {
return cur_id;
break;
} else {
cur_id = (cur_id+1)%NUM_THREADS;
}
}
return -1;
}
void*
print_sequentially(void *array) {
int index = 0;
int cur_id = (int)array;
while(1) {
pthread_mutex_lock(&count_mutex);
if(next_id == cur_id) {
cout << "TID : " << cur_id << " = " << (g_vector[cur_id])[index++] << endl;
if(index == g_vector[cur_id].size()) {
g_stat[cur_id] = true;
}
next_id = find_next_id(cur_id);
if(next_id == -1) {
pthread_mutex_unlock(&count_mutex);
exit(0);
}
}
pthread_mutex_unlock(&count_mutex);
}
}
int main() {
pthread_t threads[NUM_THREADS];
for(int i=0; i<NUM_THREADS; i++) {
for(int j=0; j<10; j++) {
g_vector[i].push_back(j);
}
}
/* Spawn 3 threads */
pthread_t thread1, thread2, thread3;
for (int i=0; i<NUM_THREADS; i++) {
pthread_create(&threads[i], NULL, &print_sequentially, (void*)i);
}
/* Join all the threads */
for (int i=0; i<NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
}
It produces the output below
TID : 0 = 0
TID : 1 = 0
TID : 2 = 0
TID : 0 = 1
TID : 1 = 1
TID : 2 = 1
TID : 0 = 2
TID : 1 = 2
TID : 2 = 2
TID : 0 = 3
TID : 1 = 3
TID : 2 = 3
TID : 0 = 4
TID : 1 = 4
TID : 2 = 4
TID : 0 = 5
TID : 1 = 5
TID : 2 = 5
TID : 0 = 6
TID : 1 = 6
TID : 2 = 6
TID : 0 = 7
TID : 1 = 7
TID : 2 = 7
TID : 0 = 8
TID : 1 = 8
TID : 2 = 8
TID : 0 = 9
TID : 1 = 9
TID : 2 = 9
package Banking;
import java.util.ArrayList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Semaphores {
CountingSemaphores lock1=new CountingSemaphores(0);
CountingSemaphores lock2=new CountingSemaphores(0);
CountingSemaphores lock3=new CountingSemaphores(1);
private Lock lock=new ReentrantLock();
private ArrayList<Integer>list1=new ArrayList<Integer>();
private ArrayList<Integer>list2=new ArrayList<Integer>();
private ArrayList<Integer>list3=new ArrayList<Integer>();
private void init()
{
int[] a={1,2,3,4,5,6,7};
for(int i:a)
list1.add(i);
int[] b={11,22,33,44,55,66,77};
for(int i:b)
list2.add(i);
int[] c={111,222,333,444,555,666,777};
for(int i:c)
list3.add(i);
}
public Semaphores()
{
init();
}
public void first(int index) throws InterruptedException
{
lock3.acquireLock();
try{
Thread.sleep(100);
System.out.println("First"+list1.get(index));
}
finally{
lock1.releaseLock();
}
}
public void second(int index) throws InterruptedException
{
lock1.acquireLock();
try{
Thread.sleep(100);
System.out.println("Second"+list2.get(index));
}
finally{
lock2.releaseLock();
}
}
public void third(int index) throws InterruptedException
{
lock2.acquireLock();
try{
Thread.sleep(100);
System.out.println("Third"+list3.get(index));
}
finally{
lock3.releaseLock();
}
}
public static void main(String [] args) throws InterruptedException
{
final Semaphores semaphore=new Semaphores();
Thread one=new Thread(new Runnable() {
int index=0;
@Override
public void run() {
try {
while(index<4)
{
semaphore.first(index);
index++;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread two=new Thread(new Runnable() {
int index=0;
@Override
public void run() {
try {
while(index<4)
{
semaphore.second(index);
index+=1;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread three=new Thread(new Runnable() {
int index=0;
@Override
public void run() {
try {
while(index<4)
{
semaphore.third(index);
index++;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
one.start();
two.start();
three.start();
one.join();
two.join();
three.join();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using ILDisasam;
using System.Threading;
namespace CSharpKTest
{
class Program
{
static ArrayList list1 = new ArrayList() { 1, 2, 3, 4, 5, 6};
static ArrayList list2 = new ArrayList() { 11, 22, 33, 44, 55, 66 };
static ArrayList list3 = new ArrayList() { 111, 222, 333, 444, 555, 666 };
static ManualResetEvent t1 = new ManualResetEvent(false);
static ManualResetEvent t2 = new ManualResetEvent(false);
static ManualResetEvent t3 = new ManualResetEvent(false);
internal class ThreadArgs
{
public int tid;
public ArrayList list;
public ThreadArgs(ArrayList lis, int id)
{
tid = id;
list = lis;
}
}
static void Main(string[] args)
{
ParameterizedThreadStart start = new ParameterizedThreadStart(ThreadImpl);
Thread t1 = new Thread(start);
Thread t2 = new Thread(start);
Thread t3 = new Thread(start);
t1.Start(new ThreadArgs(list1, 1));
t2.Start(new ThreadArgs(list2, 2));
t3.Start(new ThreadArgs(list3, 3));
}
static void ThreadImpl(object obj)
{
ThreadArgs args = obj as ThreadArgs;
ArrayList list = args.list;
int tid = args.tid;
int i=0;
t1.Set();
while (i <= list.Count)
{
if (tid == 1)
{
if (i < list.Count)
{
t1.WaitOne();
Console.WriteLine(list[i]);
t1.Reset();
}
t2.Set();
}
if (tid == 2)
{
if (i < list.Count)
{
t2.WaitOne();
Console.WriteLine(list[i]);
t2.Reset();
}
t3.Set();
}
if (tid == 3)
{
if (i < list.Count)
{
t3.WaitOne();
Console.WriteLine(list[i]);
t3.Reset();
}
t1.Set();
}
i++;
}
}
}
}
public class Program2{
private List<Integer> list1 = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 });
private List<Integer> list2 = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 });
private List<Integer> list3 = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 });
private int listSize = 5;
private int counter = 1;
private static Program2 program = null;
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
}
private Program2() {
}
private Thread thread1Start(){
Runnable r = new Runnable() {
@Override
public void run() {
int i = 0;
while(i < listSize){
synchronized(program){
if(counter!=1){
try {
program.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
System.out.println(list1.get(i++)+" from "+Thread.currentThread().getName());
counter=2;
program.notifyAll();
}
}
}
}
};
Thread t = new Thread(r, "List_1");
return t;
}
private Thread thread2Start(){
Runnable r = new Runnable() {
@Override
public void run() {
int i = 0;
while(i < listSize){
synchronized(program){
if(counter!=2){
try {
program.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
System.out.println(list2.get(i++)+" from "+Thread.currentThread().getName());
counter=3;
program.notifyAll();
}
}
}
}
};
Thread t = new Thread(r, "List_2");
return t;
}
private Thread thread3Start(){
Runnable r = new Runnable() {
@Override
public void run() {
int i = 0;
while(i < listSize){
synchronized(program){
if(counter!=3){
try {
program.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
System.out.println(list3.get(i++)+" from "+Thread.currentThread().getName());
counter=1;
program.notifyAll();
}
}
}
}
};
Thread t = new Thread(r, "List_3");
return t;
}
public static void start(){
program = new Program2();
program.thread1Start().start();
program.thread2Start().start();
program.thread3Start().start();
}
public static void main(String[] args) {
Program2.start();
}
Following program works but any idea why 'sleep' is really needed? I think program though prints expected output as it needs 'sleep', its not correct. Please help me understand why it doesnt work without sleep?
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
char l1[]={'a','b','c','d','e'};
char l2[]={'l','m','n','o','p'};
char l3[]={'u','v','w','x','y'};
int count1, count2, count3;
#define NTHREADS 3
pthread_mutex_t mutexes[NTHREADS] = {PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER,PTHREAD_MUTEX_INITIALIZER};
pthread_cond_t conditions[NTHREADS] = {PTHREAD_COND_INITIALIZER,PTHREAD_COND_INITIALIZER,PTHREAD_COND_INITIALIZER};
typedef struct{
int tid;
int printed;
int size;
char *buffer;
}thread_data;
void* thread(void *arg)
{
thread_data *data = (thread_data*)arg;
int tid = data->tid;
int printed = 0;
int size = data->size;
while(1)
{
pthread_mutex_lock(&mutexes[tid]);
pthread_cond_wait(&conditions[tid],&mutexes[tid]);
fprintf(stderr,"thread: %d item: %c\n",tid,
data->buffer[printed%size]);
printed++;
data->printed=printed;
pthread_mutex_unlock(&mutexes[tid]);
sleep(1); // why is it needed?
pthread_mutex_lock(&mutexes[(tid+1)%NTHREADS]);
pthread_cond_signal(&conditions[ (tid+1)%NTHREADS ]);
pthread_mutex_unlock(&mutexes[(tid+1)%NTHREADS]);
}
}
void init_thread_data(thread_data *data, int tid, int size, char *buffer)
{
data->tid = tid;
data->size = size;
data->buffer = buffer;
data->printed = 0;
}
int main(int argc, char *argv[])
{
thread_data data1, data2, data3;
init_thread_data(&data1, 0, sizeof(l1), l1);
init_thread_data(&data2, 1, sizeof(l2), l2);
init_thread_data(&data3, 2, sizeof(l3), l3);
pthread_t t1, t2, t3;
pthread_create(&t1, 0, thread, &data1);
pthread_create(&t2, 0, thread, &data2);
pthread_create(&t3, 0, thread, &data3);
sleep(2);
pthread_mutex_lock(&mutexes[0]);
pthread_cond_signal(&conditions[0]);
pthread_mutex_unlock(&mutexes[0]);
pthread_join(t1,0);
pthread_join(t2,0);
pthread_join(t3,0);
return 0;
}
Another piece of code that works with just one mutex and one condition variable, it works without needing sleep, basically broadcast instead of signal and checking for a 'turn' of a thread did the trick. it doesnt need sleep but since it prints too fast i have added it to catch up with its speed.
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
char l1[]={'a','b','c','d','e'};
char l2[]={'l','m','n','o','p'};
char l3[]={'u','v','w','x','y'};
#define NTHREADS 3
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c = PTHREAD_COND_INITIALIZER;
int turn = 0;
typedef struct{
int tid;
int printed;
int size;
char *buffer;
}thread_data;
void* thread(void *arg)
{
thread_data *data = (thread_data*)arg;
int tid = data->tid;
int printed = 0;
int size = data->size;
while(1)
{
pthread_mutex_lock(&m);
while(turn != tid )
pthread_cond_wait(&c,&m);
sleep(1);//sleep to print slowly, program works without sleep too!
fprintf(stderr,"thread: %d item: %c\n",tid,
data->buffer[printed%size]);
data->printed = printed++;
turn = (tid+1)%NTHREADS;
pthread_cond_broadcast(&c);
pthread_mutex_unlock(&m);
}
}
void init_thread_data(thread_data *data, int tid, int size, char *buffer)
{
data->tid = tid;
data->size = size;
data->buffer = buffer;
data->printed = 0;
}
int main(int argc, char *argv[])
{
thread_data data1, data2, data3;
init_thread_data(&data1, 0, sizeof(l1), l1);
init_thread_data(&data2, 1, sizeof(l2), l2);
init_thread_data(&data3, 2, sizeof(l3), l3);
pthread_t t1, t2, t3;
pthread_create(&t1, 0, thread, &data1);
pthread_create(&t2, 0, thread, &data2);
pthread_create(&t3, 0, thread, &data3);
sleep(2);
pthread_mutex_lock(&m);
turn=0;
pthread_cond_signal(&c);
pthread_mutex_unlock(&m);
pthread_join(t1,0);
pthread_join(t2,0);
pthread_join(t3,0);
return 0;
}
Here is a solution using AtomicBoolean variables as flags for signalling between threads.
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
public class ListTraversers {
public static void demo() {
final List<Integer> twos = Arrays.asList(new Integer[] { 2, 4, 6, 8, 10 });
final List<Integer> threes = Arrays.asList(new Integer[] { 3, 6, 9, 12, 15 });
final List<Integer> fives = Arrays.asList(new Integer[] { 5, 10, 15, 20, 25 });
final AtomicBoolean flag1 = new AtomicBoolean(false);
final AtomicBoolean flag2 = new AtomicBoolean(false);
final AtomicBoolean flag3 = new AtomicBoolean(false);
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < twos.size(); i++) {
if (i == 0) {
System.out.println(Thread.currentThread().getId() + ": " + twos.get(0));
} else {
while (!flag3.get()) {
}
while (flag1.get()) {
}
System.out.println(Thread.currentThread().getId() + ": " + twos.get(i));
}
flag3.set(false);
flag1.set(true);
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (Integer num : threes) {
while (!flag1.get()) {
}
while (flag2.get()) {
}
System.out.println(Thread.currentThread().getId() + ": " + num);
flag1.set(false);
flag2.set(true);
}
}
});
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
for (Integer num : fives) {
while (!flag2.get()) {
}
while (flag3.get()) {
}
System.out.println(Thread.currentThread().getId() + ": " + num);
flag2.set(false);
flag3.set(true);
}
}
});
t1.start();
t2.start();
t3.start();
}
public static void main(String[] args) {
demo();
}
}
A solution using java.util.concurrent tools:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
private static final int NUM_THREADS = 3;
private static final int LIST_SIZE = 10;
public static void main(String[] args) {
Lock lock = new ReentrantLock();
List<Condition> conditions = new ArrayList<Condition>();
for (int i = 0; i < NUM_THREADS; ++i) {
conditions.add(lock.newCondition());
}
ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS);
for (int i = 0; i < NUM_THREADS; ++i) {
exec.execute(new Task(i, lock, conditions, makeData(i)));
}
try {
// Wait a bit so that all threads have already started
Thread.sleep(100);
lock.lock();
conditions.get(0).signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
exec.shutdown();
}
private static List<String> makeData(int i) {
List<String> data = new ArrayList<String>();
for (int j = 0; j < LIST_SIZE; ++j) {
data.add(String.format("Thread %d, element %d.\n", i, j));
}
return data;
}
private static class Task implements Runnable {
private final int id;
private final Lock lock;
private final List<Condition> conditions;
private final List<String> data;
@Override
public void run() {
for (String s : data) {
try {
lock.lock();
conditions.get(id).await();
System.out.println(s);
conditions.get((id + 1) % conditions.size()).signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
public Task(int id, Lock lock, List<Condition> conditions, List<String> data) {
super();
this.id = id;
this.lock = lock;
this.conditions = conditions;
this.data = data;
}
}
}
66 //thread prototypes
67 void* thread0(void *data) {
68
69 int i = 0;
70 while(i<10) {
71 sem_wait(&mutex[0]);
72 printf("0");
73 sem_post(&mutex[1]);
74 i++;
75 }
76 return NULL;
77
78 }
79
80 void* thread1(void *data) {
81 int i = 0;
82 while(i<10) {
83 sem_wait(&mutex[1]);
84 printf("1");
85 sem_post(&mutex[2]);
86 i++;
87 }
88 return NULL;
89 }
91 void* thread2(void *data) {
92
93 int i = 0;
94 while(i<10) {
95 sem_wait(&mutex[2]);
96 printf("2");
97 sem_post(&mutex[0]);
98 i++;
99 }
100 return NULL;
101 }
111 void sync_threads() {
112
113 //init the mutex variables
114 init_mutex();
115
116 //create thread ids
117 pthread_t tid[THREADS];
118
119 pthread_create(&tid[0], NULL, thread0, NULL);
120 pthread_create(&tid[1], NULL, thread1, NULL);
121 pthread_create(&tid[2], NULL, thread2, NULL);
122
123 pthread_join(tid[0], NULL);
124 pthread_join(tid[1], NULL);
125 pthread_join(tid[2], NULL);
126
127 sem_destroy(&mutex[0]);
128 sem_destroy(&mutex[1]);
129 sem_destroy(&mutex[2]);
130 }
131
int main() {
sync_threads();
}
package com.practice.thread.concurrent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class PrintListOrder {
public static void main(String[] args) {
final List<Integer> l1 = new ArrayList<>(Arrays.asList(1, 4, 7, 10, 13));
final List<Integer> l2 = new ArrayList<>(Arrays.asList(2, 5, 8, 11, 14));
final List<Integer> l3 = new ArrayList<>(Arrays.asList(3, 6, 9, 12, 15));
final Lock lock = new ReentrantLock();
final Condition condition = lock.newCondition();
final ThreadId id = new PrintListOrder.ThreadId();
id.setId(1);
Thread t1 = getThread(lock, condition, 1, 2, l1, id);
Thread t2 = getThread(lock, condition, 2, 3, l2, id);
Thread t3 = getThread(lock, condition, 3, 1, l3, id);
t1.start();
t2.start();
t3.start();
}
static class ThreadId {
private int id;
public void setId(int i) {
id = i;
}
public int getid() {
return id;
}
}
public static Thread getThread(Lock lock, Condition condition, int currentThreadId, int nextthreadID,
List<Integer> list, ThreadId id) {
Thread t = new Thread() {
public void run() {
for (Integer i : list) {
try {
lock.lock();
while (currentThreadId != id.getid())
try {
condition.await();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
System.out.println(i.toString());
id.setId(nextthreadID);
condition.signalAll();
} finally {
lock.unlock();
}
}
}
};
return t;
}
}
ublic class Thread1Work implements Runnable {
List<Integer> ls1;
SharedObjectlist shared;
public Thread1Work(List<Integer> ls1, SharedObjectlist shared) {
super();
this.ls1 = ls1;
this.shared = shared;
}
@Override
public void run() {
int s=ls1.size();
for(int i=0;i<ls1.size();i++) {
synchronized(shared) {
if(shared.flag!=1) {
try {
shared.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
System.out.println( ls1.get(i));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
shared.flag=2;
shared.notifyAll();
}}
}
}
}
ublic class Thread1Work implements Runnable {
List<Integer> ls1;
SharedObjectlist shared;
public Thread1Work(List<Integer> ls1, SharedObjectlist shared) {
super();
this.ls1 = ls1;
this.shared = shared;
}
@Override
public void run() {
int s=ls1.size();
for(int i=0;i<ls1.size();i++) {
synchronized(shared) {
if(shared.flag!=1) {
try {
shared.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
System.out.println( ls1.get(i));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
shared.flag=2;
shared.notifyAll();
}}
}
}}
ublic class Thread1Work implements Runnable {
List<Integer> ls1;
SharedObjectlist shared;
public Thread1Work(List<Integer> ls1, SharedObjectlist shared) {
super();
this.ls1 = ls1;
this.shared = shared;
}
@Override
public void run() {
int s=ls1.size();
for(int i=0;i<ls1.size();i++) {
synchronized(shared) {
if(shared.flag!=1) {
try {
shared.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
System.out.println( ls1.get(i));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
shared.flag=2;
shared.notifyAll();
}}
}
}
}
This works
- Anonymous April 06, 2013