Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C#
  4. Mutlithreading application threading and semaphores?

Mutlithreading application threading and semaphores?

Scheduled Pinned Locked Moved C#
csharptutorialquestionannouncement
7 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    auting82
    wrote on last edited by
    #1

    Hi I am trying to develop a multitasking application in C# based on some code I have available that is depicted below. I have tried to do some changes but I am not sure if I put the WaitOne() and Release() methods at the correct places. I am trying to include semaphore for a secure usage of common resources. A semaphore is defined in C# by making a "Semaphore" variable, and use the methods WaitOne() and Release() to access the semaphore services. I want to include name, student number and the semester year in the display information. Sleep(0) statements can be used to test the sharing of common resources. I will use a console application. The print out in console should be something like: [T1]: Student no. [T1]: Student name [T1]: Semester year [T2]: Student no. [T2]: Student name [T2]: Semester year [T1]: Student no. [T3]: Student no. [T1]: Student name [T2]: Student name

    using System;
    using System.Threading;
    //Example in using sleep() and Threads in C#
    namespace ThreadSys
    {
    /// /// Threadclass
    ///
    class ThreadClass
    {
    int loopCnt, loopDelay;
    Thread cThread;
    public string studentname;
    static Semaphore semaphore = new Semaphore(1,1);
    public ThreadClass(string name, int delay)
    {
    loopCnt = 0;
    loopDelay = delay;
    cThread = new Thread(new ThreadStart(this.run));
    cThread.Name = name;

            cThread.Start();
        }
        // The main function in the ThreadClass
        void run()
        {
            Console.WriteLine(" Starting " + cThread.Name);
            do
            {
                loopCnt++;
                Thread.Sleep(loopDelay);
                Console.Write(" ");
                semaphore.WaitOne();
                Console.Write(cThread.Name);
                
                Console.Write(": ");
                Console.WriteLine("Loop=" + loopCnt);
                
                semaphore.Release();
    
            } while (loopCnt < 5);
            // Ending of the thread
            Console.WriteLine(" Ending " + cThread.Name);
    
        }
    }
    
    // The application
    class ThreadSys
    {
        /// /// Start of the main program
        /// 
        static void Main(string\[\] args)
        {
            Console.WriteLine(" Start of main program ");
            // Making 3 threads ..
            ThreadClass ct1 = new
    
    L B 3 Replies Last reply
    0
    • A auting82

      Hi I am trying to develop a multitasking application in C# based on some code I have available that is depicted below. I have tried to do some changes but I am not sure if I put the WaitOne() and Release() methods at the correct places. I am trying to include semaphore for a secure usage of common resources. A semaphore is defined in C# by making a "Semaphore" variable, and use the methods WaitOne() and Release() to access the semaphore services. I want to include name, student number and the semester year in the display information. Sleep(0) statements can be used to test the sharing of common resources. I will use a console application. The print out in console should be something like: [T1]: Student no. [T1]: Student name [T1]: Semester year [T2]: Student no. [T2]: Student name [T2]: Semester year [T1]: Student no. [T3]: Student no. [T1]: Student name [T2]: Student name

      using System;
      using System.Threading;
      //Example in using sleep() and Threads in C#
      namespace ThreadSys
      {
      /// /// Threadclass
      ///
      class ThreadClass
      {
      int loopCnt, loopDelay;
      Thread cThread;
      public string studentname;
      static Semaphore semaphore = new Semaphore(1,1);
      public ThreadClass(string name, int delay)
      {
      loopCnt = 0;
      loopDelay = delay;
      cThread = new Thread(new ThreadStart(this.run));
      cThread.Name = name;

              cThread.Start();
          }
          // The main function in the ThreadClass
          void run()
          {
              Console.WriteLine(" Starting " + cThread.Name);
              do
              {
                  loopCnt++;
                  Thread.Sleep(loopDelay);
                  Console.Write(" ");
                  semaphore.WaitOne();
                  Console.Write(cThread.Name);
                  
                  Console.Write(": ");
                  Console.WriteLine("Loop=" + loopCnt);
                  
                  semaphore.Release();
      
              } while (loopCnt < 5);
              // Ending of the thread
              Console.WriteLine(" Ending " + cThread.Name);
      
          }
      }
      
      // The application
      class ThreadSys
      {
          /// /// Start of the main program
          /// 
          static void Main(string\[\] args)
          {
              Console.WriteLine(" Start of main program ");
              // Making 3 threads ..
              ThreadClass ct1 = new
      
      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      It's not really a very good test as there is nothing that is shared between the threads. You could try using a common memory buffer, where one thread puts data into it, and the other takes data out.

      A 1 Reply Last reply
      0
      • L Lost User

        It's not really a very good test as there is nothing that is shared between the threads. You could try using a common memory buffer, where one thread puts data into it, and the other takes data out.

        A Offline
        A Offline
        auting82
        wrote on last edited by
        #3

        This is more of a simulation of a multitask application. The only thing I was trying to do here is to make some slight changes to the code so that I get print outs where Tasks [T1], [T2] and [T3] are not only printing out sequnetally but kind of roandomly in sort of random order. However my C# coding abilites are worse than I would imagine so getting this done anytime soon aitn gonna happen. Furthermore, I couldnt find anything on this Threadclass in C#. I didnt see any examples online where this ThreadClass was used directly in the code.

        D L 2 Replies Last reply
        0
        • A auting82

          This is more of a simulation of a multitask application. The only thing I was trying to do here is to make some slight changes to the code so that I get print outs where Tasks [T1], [T2] and [T3] are not only printing out sequnetally but kind of roandomly in sort of random order. However my C# coding abilites are worse than I would imagine so getting this done anytime soon aitn gonna happen. Furthermore, I couldnt find anything on this Threadclass in C#. I didnt see any examples online where this ThreadClass was used directly in the code.

          D Offline
          D Offline
          Dave Kreskowiak
          wrote on last edited by
          #4

          auting82 wrote:

          I couldnt find anything on this Threadclass in C#.

          Of course you didn't. It's not part of the .NET Framework. It's code YOU WROTE, so why would you expect there to be any documentation on it anywhere? Threads do not run in sequential order, and cannot be predicted to execute in any determined order. It's not the code that is wrong, but your expectations of how the system will execute it.

          Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
          Dave Kreskowiak

          1 Reply Last reply
          0
          • A auting82

            This is more of a simulation of a multitask application. The only thing I was trying to do here is to make some slight changes to the code so that I get print outs where Tasks [T1], [T2] and [T3] are not only printing out sequnetally but kind of roandomly in sort of random order. However my C# coding abilites are worse than I would imagine so getting this done anytime soon aitn gonna happen. Furthermore, I couldnt find anything on this Threadclass in C#. I didnt see any examples online where this ThreadClass was used directly in the code.

            L Offline
            L Offline
            Lost User
            wrote on last edited by
            #5

            Well you created the ThreadClass so why would you expect to find examples of it on the internet? However, there is some sample code at Thread Class (System.Threading) | Microsoft Docs[^]. Also, if your coding skills are as basic as you imply, then I suggest you stay well clear of threads, they rarely offer any benefit unless you are creating large multitasking applications.

            1 Reply Last reply
            0
            • A auting82

              Hi I am trying to develop a multitasking application in C# based on some code I have available that is depicted below. I have tried to do some changes but I am not sure if I put the WaitOne() and Release() methods at the correct places. I am trying to include semaphore for a secure usage of common resources. A semaphore is defined in C# by making a "Semaphore" variable, and use the methods WaitOne() and Release() to access the semaphore services. I want to include name, student number and the semester year in the display information. Sleep(0) statements can be used to test the sharing of common resources. I will use a console application. The print out in console should be something like: [T1]: Student no. [T1]: Student name [T1]: Semester year [T2]: Student no. [T2]: Student name [T2]: Semester year [T1]: Student no. [T3]: Student no. [T1]: Student name [T2]: Student name

              using System;
              using System.Threading;
              //Example in using sleep() and Threads in C#
              namespace ThreadSys
              {
              /// /// Threadclass
              ///
              class ThreadClass
              {
              int loopCnt, loopDelay;
              Thread cThread;
              public string studentname;
              static Semaphore semaphore = new Semaphore(1,1);
              public ThreadClass(string name, int delay)
              {
              loopCnt = 0;
              loopDelay = delay;
              cThread = new Thread(new ThreadStart(this.run));
              cThread.Name = name;

                      cThread.Start();
                  }
                  // The main function in the ThreadClass
                  void run()
                  {
                      Console.WriteLine(" Starting " + cThread.Name);
                      do
                      {
                          loopCnt++;
                          Thread.Sleep(loopDelay);
                          Console.Write(" ");
                          semaphore.WaitOne();
                          Console.Write(cThread.Name);
                          
                          Console.Write(": ");
                          Console.WriteLine("Loop=" + loopCnt);
                          
                          semaphore.Release();
              
                      } while (loopCnt < 5);
                      // Ending of the thread
                      Console.WriteLine(" Ending " + cThread.Name);
              
                  }
              }
              
              // The application
              class ThreadSys
              {
                  /// /// Start of the main program
                  /// 
                  static void Main(string\[\] args)
                  {
                      Console.WriteLine(" Start of main program ");
                      // Making 3 threads ..
                      ThreadClass ct1 = new
              
              L Offline
              L Offline
              Lost User
              wrote on last edited by
              #6

              Try an example that works; then get creative. [Thread Class (System.Threading) | Microsoft Docs](https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread?view=netframework-4.8)

              It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it. ― Confucian Analects: Rules of Confucius about his food

              1 Reply Last reply
              0
              • A auting82

                Hi I am trying to develop a multitasking application in C# based on some code I have available that is depicted below. I have tried to do some changes but I am not sure if I put the WaitOne() and Release() methods at the correct places. I am trying to include semaphore for a secure usage of common resources. A semaphore is defined in C# by making a "Semaphore" variable, and use the methods WaitOne() and Release() to access the semaphore services. I want to include name, student number and the semester year in the display information. Sleep(0) statements can be used to test the sharing of common resources. I will use a console application. The print out in console should be something like: [T1]: Student no. [T1]: Student name [T1]: Semester year [T2]: Student no. [T2]: Student name [T2]: Semester year [T1]: Student no. [T3]: Student no. [T1]: Student name [T2]: Student name

                using System;
                using System.Threading;
                //Example in using sleep() and Threads in C#
                namespace ThreadSys
                {
                /// /// Threadclass
                ///
                class ThreadClass
                {
                int loopCnt, loopDelay;
                Thread cThread;
                public string studentname;
                static Semaphore semaphore = new Semaphore(1,1);
                public ThreadClass(string name, int delay)
                {
                loopCnt = 0;
                loopDelay = delay;
                cThread = new Thread(new ThreadStart(this.run));
                cThread.Name = name;

                        cThread.Start();
                    }
                    // The main function in the ThreadClass
                    void run()
                    {
                        Console.WriteLine(" Starting " + cThread.Name);
                        do
                        {
                            loopCnt++;
                            Thread.Sleep(loopDelay);
                            Console.Write(" ");
                            semaphore.WaitOne();
                            Console.Write(cThread.Name);
                            
                            Console.Write(": ");
                            Console.WriteLine("Loop=" + loopCnt);
                            
                            semaphore.Release();
                
                        } while (loopCnt < 5);
                        // Ending of the thread
                        Console.WriteLine(" Ending " + cThread.Name);
                
                    }
                }
                
                // The application
                class ThreadSys
                {
                    /// /// Start of the main program
                    /// 
                    static void Main(string\[\] args)
                    {
                        Console.WriteLine(" Start of main program ");
                        // Making 3 threads ..
                        ThreadClass ct1 = new
                
                B Offline
                B Offline
                Bohdan Stupak
                wrote on last edited by
                #7

                Pardon me if I've misunderstood your question but it seems to me that you spawn your threads but expect them to execute synchronously which does not make any sense to me at all. So I agree with Richard that this is not the best example as it would just benefit from synchronous code as it is much simpler and as performant. My main point is that the best parallelism is when you have no shared resources between your tasks and you should strive for it. In case you wanted to simulate with your example the fact that it requires some effort to compute info about the student (i.e. you get it from DB) I would rather suggest you investigate async/await.

                1 Reply Last reply
                0
                Reply
                • Reply as topic
                Log in to reply
                • Oldest to Newest
                • Newest to Oldest
                • Most Votes


                • Login

                • Don't have an account? Register

                • Login or register to search.
                • First post
                  Last post
                0
                • Categories
                • Recent
                • Tags
                • Popular
                • World
                • Users
                • Groups