Question

How to change this C code to java? dining_philosopher.c #define N 5 /* number of philosophers...

How to change this C code to java?

dining_philosopher.c

#define N 5                   /* number of philosophers */

void philosopher(int i)       /* i: philosopher number, from 0 to 4 */
{
    while (TRUE) {
        think();              /* philosopher is thinking */
        take_fork(i);         /* take left fork */
        take_fork((i+1) % N); /* take right fork; % is modulo operator */
        eat();                /* yum-yum, spaghetti */
        put_fork(i);          /* put left fork back on the table */
        put_fork((i+1) % N);  /* put right fork back on the table */
    }
}

dining_philosopher_semaphore.c

#define N        5               /* number of philosophers */
#define LEFT     (i + N - 1) % N /* number of i's left neighbor */
#define RIGHT    (i + 1) % N     /* number of i's right neighbor */
#define THINKING 0               /* philosopher is thinking */
#define HUNGRY   1               /* philosopher is trying to get forks */
#define EATING   2               /* philosopher is eating */

typedef int semaphore;           /* semaphores are a special kind of int */
int state[N];                    /* array to keep track of everyone's state */
semaphore mutex = 1 ;            /* mutual exclusion for critical regions */
semaphore s[N];                  /* one semaphore per philosopher */

void philosopher(int i)          /* i: philosopher number, from 0 to N-1 */
{
    while (TRUE) {               /* repeat forever */
        think( );                /* philosopher is thinking */
        take_forks(i);           /* acquire two forks or block */
        eat();                   /* yum-yum, spaghetti */
        put_forks(i);            /* put both forks back on table */
    }
}

void take_forks(int i)           /* i: philosopher number, from 0 to N-1 */
{
    down(&mutex);                /* enter critical region */
    state[i] = HUNGRY;           /* record fact that philosopher i is hungry */
    test(i);                     /* try to acquire 2 forks */
    up(&mutex);                  /* exit critical region */
    down(&s[i]);                 /* block if forks were not acquired */
}

void put_forks(i)                /* i: philosopher number, from 0 to N-1 */
{
    down(&mutex);                /* enter critical region */
    state[i] = THINKING;         /* philosopher has finished eating */
    test(LEFT);                  /* see if left neighbor can now eat */
    test(RIGHT);                 /* see if right neighbor can now eat */
    up(&mutex);                  /* exit critical region */
}

void test(i)                     /* i: philosopher number, from 0 to N-1 */
{
    if(state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING) {
        state[i] = EATING;
        up(&s[i]);
    }
}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

For changing the code from C to Java you can implement dining philosopher problem using Java.

Below is the Java code for solving Dining Philosopher problem.

Code:


import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadLocalRandom;

public class Main {

static int philosopher = 5;
static philosopher philosophers[] = new philosopher[philosopher];
static chopstick chopsticks[] = new chopstick[philosopher];

static class chopstick {

public Semaphore mutex = new Semaphore(1);

void grab() {
try {
mutex.acquire();
}
catch (Exception e) {
e.printStackTrace(System.out);
}
}

void release() {
mutex.release();
}

boolean isFree() {
return mutex.availablePermits() > 0;
}

}

static class philosopher extends Thread {

public int number;
public chopstick leftchopstick;
public chopstick rightchopstick;

philosopher(int num, chopstick left, chopstick right) {
number = num;
leftchopstick = left;
rightchopstick = right;
}

public void run(){

while (true) {
leftchopstick.grab();
System.out.println("philosopher " + (number+1) + " grabs left chopstick.");
rightchopstick.grab();
System.out.println("philosopher " + (number+1) + " grabs right chopstick.");
eat();
leftchopstick.release();
System.out.println("philosopher " + (number+1) + " releases left chopstick.");
rightchopstick.release();
System.out.println("philosopher " + (number+1) + " releases right chopstick.");
}
}

void eat() {
try {
int sleepTime = ThreadLocalRandom.current().nextInt(0, 1000);
System.out.println("philosopher " + (number+1) + " eats for " + sleepTime);
Thread.sleep(sleepTime);
}
catch (Exception e) {
e.printStackTrace(System.out);
}
}

}

public static void main(String argv[]) {

for (int i = 0; i < philosopher; i++) {
chopsticks[i] = new chopstick();
}

for (int i = 0; i < philosopher; i++) {
philosophers[i] = new philosopher(i, chopsticks[i], chopsticks[(i + 1) % philosopher]);
philosophers[i].start();
}

while (true) {
try {
// sleep 1 sec
Thread.sleep(1000);

// check for deadlock
boolean deadlock = true;
for (chopstick f : chopsticks) {
if (f.isFree()) {
deadlock = false;
break;
}
}
if (deadlock) {
Thread.sleep(1000);
System.out.println("Everyone Eats");
break;
}
}
catch (Exception e) {
e.printStackTrace(System.out);
}
}

System.out.println("Exit The Program!");
System.exit(0);
}

}

Output Screenshot:

An upvote would be really helpful!

Add a comment
Know the answer?
Add Answer to:
How to change this C code to java? dining_philosopher.c #define N 5 /* number of philosophers...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Using the following pseudocode write a c program that solves the dining philosophers problem. #define N...

    Using the following pseudocode write a c program that solves the dining philosophers problem. #define N 5 #define LEFT (i+N-1)%N #define RIGHT (i+1)%N #define THINKING 0 #define HUNGRY 1 #define EATING 2 typedef int semaphore; int state[N]; semaphore mutex = 1; semaphore s[N]; void philosopher(int i) { while(TRUE) { think(); take_forks(i); eat(); put_forks(i); } } void take_forks(int i) { down(&mutex); state[i] = HUNGRY; test(i); up(&mutex); down(&s[i]); } void put_forks(i) { down(&mutex); state[i] = THINKING; test(LEFT); test(RIGHT); up(&mutex); } void test(i)...

  • What are the three requirements for a solution to the critical-section problem? Consider the following solution...

    What are the three requirements for a solution to the critical-section problem? Consider the following solution to the dining-philosophers' problem. // Global variables. Shared among threads int state [5]; semaphore mutex; I/ Initially set to 1 semaphore s [5] I Initially s[i] is set to 0 for all i Initially statei]-THINKING for all i void philosopher (int i) f int left(int i) f // Philosopher to the left of i // % is the mod operator. while(TRUE) thinkO take.forks ()...

  • Consider the Dining-Philosophers problem (Chapter 5.7.3), in which a set of philosophers sit around a table...

    Consider the Dining-Philosophers problem (Chapter 5.7.3), in which a set of philosophers sit around a table with one chopstick between each of them. Let the philosophers be numbered from 0 to n−1 and be represented by separate threads. Each philosopher executes Dine(i), where “i” is the philosopher’s number. Assume that there is an array of semaphores, Chop[i] that represents the chopstick to the left of philosopher i. These semaphores are initialized to 1. void Dine( int i ) { Chop[...

  • operating system engineering , please read the question and solve on the given skeleton code ....

    operating system engineering , please read the question and solve on the given skeleton code . Write a multi-threaded program with Semaphores as counters and pthread_mutex_t mutex to solve the producer-consumer problem: A bounded buffer is simply a global integer array of size N (2) which can be accessed by multiple threads. • Create two types of threads - Producer (2) and Consumer (2). Producers will write to the buffer, and the consumers will read the buffer. In this scenario,...

  • CONVERT CODE TO JAVA // A C++ program to Print all elements in sorted order from...

    CONVERT CODE TO JAVA // A C++ program to Print all elements in sorted order from row and // column wise sorted matrix #include<iostream> #include<climits> using namespace std;    #define INF INT_MAX #define N 4    // A utility function to youngify a Young Tableau. This is different // from standard youngify. It assumes that the value at mat[0][0] is // infinite. void youngify(int mat[][N], int i, int j) {     // Find the values at down and right sides of...

  • C PROGRAM The following is code prints the current activation record number, the memory address of...

    C PROGRAM The following is code prints the current activation record number, the memory address of the current array, followed by the estimated size of the current activation record as a distance between the current array address and the array address from the previous activation record. I need it to run until a segmentation fault occurs and also it must print the estimated size of the runtime stack as a product of the size of current activation record and the...

  • Please write where its written write your code here!! please use java for the code! please...

    Please write where its written write your code here!! please use java for the code! please use the given code and I will rate thanks Magic index in an array a[1..n] is defined to be an index such that a[ i ] = i. Given an array of integers, write a recursive method to find the first magic index from left to right. If one exists in the given array, return the index number i, otherwise return -1. Here are...

  • please make a pretty JAVA GUI for this code this is RED BLACK TREE and i...

    please make a pretty JAVA GUI for this code this is RED BLACK TREE and i Finished code already jus need a JAVA GUI for this code ... if poosible make it pretty to look thanks and please make own GUI code base on my code thanks ex: (GUI only have to show RBTree) ---------------------------------------- RBTree.java import java.util.Stack; public class RBTree{    private Node current;    private Node parent;    private Node grandparent;    private Node header;    private Node...

  • I have C++ code. How I can change to Java code #include <iostream> using namespace std;...

    I have C++ code. How I can change to Java code #include <iostream> using namespace std; int initialNumber[4]; int main() {    void ShowResult();       //initialization    int NuberOfpage[20]={1,0,7,1,0,2,1,2,3,0,3,2,4,0,3,0,2,1,0,7},i,j,f12[3];    int num1=0,num2=0,countr=0,framsize=3;    int inital,current,current1;    for(i=0;i<3;i++) { initialNumber[i]=-1; } for(j=0;j<20;j++) { num1=0,num2=0;    for(i=0;i<3;i++) {    if(initialNumber[i]==NuberOfpage[j]) {    num1=1;    num2=1;    break; } }    if(num1==0)    { for(i=0;i<3;i++)    { if(initialNumber[i]==-1)    {    initialNumber[i]=NuberOfpage[j];    num2=1;    break; } } }    if(num2==0)   ...

  • C++ EXERCISE (DATA STRUCTURES). I just need a code for some functions that are missing. Please...

    C++ EXERCISE (DATA STRUCTURES). I just need a code for some functions that are missing. Please help me figure out. Thanks. C++ BST implementation (using a struct) Enter the code below, and then compile and run the program. After the program runs successfully, add the following functions: postorder() This function is similar to the inorder() and preorder() functions, but demonstrates postorder tree traversal. displayParentsWithTwo() This function is similar to the displayParents WithOne() function, but displays nodes having only two children....

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT