3 Replies - 4720 Views - Last Post: 24 November 2011 - 10:41 AM Rate Topic: -----

#1 quim   User is offline

  • D.I.C Head
  • member icon

Reputation: 18
  • View blog
  • Posts: 182
  • Joined: 11-December 05

Problem with C# Thread

Posted 24 November 2011 - 07:51 AM

I'm suppose to implement program using threads, using a programming language other than C.
i decided to use C# and implement a class that simulates the Dinning Philosophers.

Why only the first thread gets to run and then the program terminates?
How do i make all the treads run in parallel?
I also used the lock(),Same as Monitor.Enter(), Monitor.Exit)(), to prevent deadlock.
... i don't really know C# yet, i just coded based on what i know about java and c++ and its similarities to C#.

Here is the code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace DinningPhilosophers
{
    class Philosopher
    {
        // static variables to be used throughout the program
        const int TOTAL_PHILOSOPHERS = 5;
        static readonly object _locker = new Object();
       
        // instance variables 
        private enum Status { THINKING, HUNGRY, EATING };
        private int[] _state;   // state of each philosopher
        private string[] _name; // name of each philosopher (keep array parallel to the _state)

        public Philosopher()
        {
            System.Console.WriteLine("WELCOME TO THE DINNING PHILOSOPHERS SIMULATION");
            // initialize all instance variables
            init();
        }


        // initialize instance variables
        private void init()
        {
            _state = new int[TOTAL_PHILOSOPHERS];
            _name = new String[] { "Joaquim", "Socratis", "Plato", "Aristotle", "Karl Marx" };

            // initialize all philosophers to thinking state
            for (int i = 0; i < TOTAL_PHILOSOPHERS; i++)
            {
                _state[i] = (int)Status.THINKING;
                this.thinking(i);
            }
        }


        private void thinking(int philosId)
        {
            System.Console.WriteLine("{0,-10} is thinnking.", _name[philosId]);
        }

        private void eating(int philosId)
        {
            System.Console.ForegroundColor = ConsoleColor.Green;
            System.Console.WriteLine("{0,-10} is eating.", _name[philosId]);
            System.Console.ResetColor();
        }

        private void hungry(int philosId)
        {
            System.Console.ForegroundColor = ConsoleColor.Red;
            System.Console.WriteLine("{0,-10} is hungry.", _name[philosId]);
            System.Console.ResetColor();
        }

        private void printPickup(int philosId) 
        {
            System.Console.WriteLine("{0,-10} pickup left chopstick.", _name[philosId]);
            Thread.Sleep(1000);      // this is just for the waiting effect
            System.Console.WriteLine("{0,-10} pickup right chopstick.", _name[philosId]);
        }

        private void printPutdown(int philosId) 
        {
            System.Console.WriteLine("{0,-10} putdown the chopsticks.", _name[philosId]);
        }

        /**
         * The philosopher uses this method to putdown chopstick*/
        private void putdown(int philosId)
        {
            lock (_locker)
            {
                _state[philosId] = (int)Status.THINKING;
                this.thinking(philosId);
                this.test((philosId + 4) % TOTAL_PHILOSOPHERS); // check left philos
                this.test((philosId + 1) % TOTAL_PHILOSOPHERS); // check right philos
                this.printPutdown(philosId);
            }
        }


        /**
         * The philosopher uses this method to pickup chopstick*/
        private void pickup(int philosId)
        {
            lock (_locker)
            {
                _state[philosId] = (int)Status.HUNGRY;
                this.hungry(philosId);
                this.test(philosId);

                //if (_state[philosId] != (int)Status.EATING) {}
                Thread.Sleep(1000);
            }
        }



        /**
         * check if philosopher is hungry and attempt to feed him
         */
        private void test(int philosId)
        {
            //allow philosopher to eat if philosopher is hungry
            //the philosopher to the left/right are not eating
            if ((_state[(philosId + 4) % TOTAL_PHILOSOPHERS] != (int)Status.EATING) &&
                (_state[philosId] == (int)Status.HUNGRY &&
                (_state[(philosId + 1) % TOTAL_PHILOSOPHERS] != (int)Status.EATING)))
            {
              
                _state[philosId] = (int)Status.EATING;
                this.printPickup(philosId);
                Thread.Sleep(2000);
                this.eating(philosId);
            }

        }

        /**
         * this method runs the pickup and putdown method to simulate 
         * philosophers eating in a table.*/
        public void run(object philosId)
        {
            int id = (int) philosId;
           // while (true)
            //{
                Thread.Sleep(1000);
                this.pickup(id);
                Thread.Sleep(1000);
                this.putdown(id);
           // }
        }


        static void Main(string[] args)
        {
            Philosopher philos = new Philosopher();
            Thread[] threads = new Thread[Philosopher.TOTAL_PHILOSOPHERS];

            // initialize all threads
            for (int i = 0; i < Philosopher.TOTAL_PHILOSOPHERS; i++)
            {
                threads[i] = new Thread(new ParameterizedThreadStart(philos.run));
                System.Console.WriteLine("THREAD {0} IS BEING CREATED\n", i);
            }

            // FOR DEBUG
            System.Console.WriteLine("______________________________________\n");

            // start all thread
            for (int i = 0; i < Philosopher.TOTAL_PHILOSOPHERS; i++)
            {
                try
                {
                    System.Console.WriteLine("THREAD {0} IS BEING STARTED\n", i);
                    threads[i].Start(i);
                }
                catch (ThreadStateException e)
                {
                    Console.WriteLine(e);  // Display text of exception
                }
                catch (ThreadInterruptedException e)
                {
                    Console.WriteLine(e);
                }
            }

            // FOR DEBUG
            System.Console.WriteLine("______________________________________\n");

            // join all thread
            for (int i = 0; i < Philosopher.TOTAL_PHILOSOPHERS; i++)
            {
                try
                {
                    System.Console.WriteLine("THREAD {0} IS BEING JOINED\n", i);
                    threads[i].Join();
                }
                catch (ThreadStateException e)
                {
                    Console.WriteLine(e);  // Display text of exception
                }
                catch (ThreadInterruptedException e)
                {
                    Console.WriteLine(e);
                }
            }

            // FOR DEBUG
            System.Console.WriteLine("______________________________________\n");
        }

    }
}



Is This A Good Question/Topic? 0
  • +

Replies To: Problem with C# Thread

#2 ragingben   User is offline

  • D.I.C Addict
  • member icon

Reputation: 177
  • View blog
  • Posts: 646
  • Joined: 07-October 08

Re: Problem with C# Thread

Posted 24 November 2011 - 07:57 AM

Are you running this through a console app?
Was This Post Helpful? 0
  • +
  • -

#3 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6537
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Problem with C# Thread

Posted 24 November 2011 - 08:00 AM

We have several tutorials on threading

See FAQ #13


FAQ (Frequently Asked Questions - Updated Oct 2011

Spoiler

Was This Post Helpful? 0
  • +
  • -

#4 quim   User is offline

  • D.I.C Head
  • member icon

Reputation: 18
  • View blog
  • Posts: 182
  • Joined: 11-December 05

Re: Problem with C# Thread

Posted 24 November 2011 - 10:41 AM

View Postragingben, on 24 November 2011 - 09:57 AM, said:

Are you running this through a console app?


Yes this is a console App.
Actually all thread are joining. the issues is that some threads are not doing any job
this is the output i got when i added System.Console.ReadKey() at the end of Main

if i was using C and pthreads i know i would have
5 pthread_create() and then pthread_join() all threads, i would use semaphore and
sem_init(), sem_wait(), and sem_post() to manipulate what regions the threads can use.

i'm not sure if i'm using the right approach with C# since its object oriented. Any thoughts?



WELCOME TO THE DINNING PHILOSOPHERS SIMULATION
Joaquim    is thinnking.
Socratis   is thinnking.
Plato      is thinnking.
Aristotle  is thinnking.
Karl Marx  is thinnking.
THREAD 0 IS BEING CREATED

THREAD 1 IS BEING CREATED

THREAD 2 IS BEING CREATED

THREAD 3 IS BEING CREATED

THREAD 4 IS BEING CREATED

______________________________________

THREAD 0 IS BEING STARTED

THREAD 1 IS BEING STARTED

THREAD 2 IS BEING STARTED

THREAD 3 IS BEING STARTED

THREAD 4 IS BEING STARTED

______________________________________

THREAD 0 IS BEING JOINED

Joaquim    is hungry.
Joaquim    pickup left chopstick.
Joaquim    pickup right chopstick.
Joaquim    is eating.
Karl Marx  is hungry.
Socratis   is hungry.
Aristotle  is hungry.
Aristotle  pickup left chopstick.
Aristotle  pickup right chopstick.
Aristotle  is eating.
Plato      is hungry.
Joaquim    is thinnking.
Socratis   pickup left chopstick.
Socratis   pickup right chopstick.
Socratis   is eating.
Joaquim    putdown the chopsticks.
Karl Marx  is thinnking.
THREAD 1 IS BEING JOINED

Karl Marx  putdown the chopsticks.
Socratis   is thinnking.
Socratis   putdown the chopsticks.
Aristotle  is thinnking.
Plato      pickup left chopstick.
THREAD 2 IS BEING JOINED

Plato      pickup right chopstick.
Plato      is eating.
Aristotle  putdown the chopsticks.
Plato      is thinnking.
Plato      putdown the chopsticks.
THREAD 3 IS BEING JOINED

THREAD 4 IS BEING JOINED

______________________________________


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1