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
  1. Home
  2. General Programming
  3. C#
  4. Trying to design thread safe class

Trying to design thread safe class

Scheduled Pinned Locked Moved C#
designbeta-testingfunctionalhelpquestion
31 Posts 3 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.
  • L Offline
    L Offline
    Lost User
    wrote on last edited by
    #1

    I am somewhat beginning with threads, and I am wondering if following class is thread safe? Or in which cases it is thread safe? The idea is users should be able to initialize this class once, second time initialization should not work if deinitialization was not called. But getting the properties should give correct results... and here I am having hard time to determine in which case those properties will get correct results, and if init and deinit methods are thread safe, as well as isInited method. Help appreciated. I tried make it immutable also.

    static class Parameters
    {
    private static int x1; // only getters of x1 and x2 will be visible to outside world
    private static int x2;
    private static bool isInit;
    private static readonly object Locker = new object();

    public static bool isInited()
    {
    lock(Locker)
    {
    return isInit;
    }
    }

    public static int X1()
    {
    if(!isInited()) throw new Exception("init first");
    return x1;

    }

    public static int X2()
    {
    lock(Locker)
    {
    if(!isInited()) throw new Exception("init first");
    return x2;
    }

    }

    public static void init(int x, int y)
    {
    lock(Locker)
    {
    if(isInit) return;
    isInit = true;
    x1 = x;
    x2 = y;
    }
    }

    public static void Deinit()
    {

    lock(Locker)
    {
      if(!isInit) return;
      isInit = false;
      x1 = 0;
      x2 = 0;
    }
    

    }

    }

    Or the client - user of this class has to take additional means to ensure this class is used in thread safe manner? Feedback appreciated

    B 1 Reply Last reply
    0
    • L Lost User

      I am somewhat beginning with threads, and I am wondering if following class is thread safe? Or in which cases it is thread safe? The idea is users should be able to initialize this class once, second time initialization should not work if deinitialization was not called. But getting the properties should give correct results... and here I am having hard time to determine in which case those properties will get correct results, and if init and deinit methods are thread safe, as well as isInited method. Help appreciated. I tried make it immutable also.

      static class Parameters
      {
      private static int x1; // only getters of x1 and x2 will be visible to outside world
      private static int x2;
      private static bool isInit;
      private static readonly object Locker = new object();

      public static bool isInited()
      {
      lock(Locker)
      {
      return isInit;
      }
      }

      public static int X1()
      {
      if(!isInited()) throw new Exception("init first");
      return x1;

      }

      public static int X2()
      {
      lock(Locker)
      {
      if(!isInited()) throw new Exception("init first");
      return x2;
      }

      }

      public static void init(int x, int y)
      {
      lock(Locker)
      {
      if(isInit) return;
      isInit = true;
      x1 = x;
      x2 = y;
      }
      }

      public static void Deinit()
      {

      lock(Locker)
      {
        if(!isInit) return;
        isInit = false;
        x1 = 0;
        x2 = 0;
      }
      

      }

      }

      Or the client - user of this class has to take additional means to ensure this class is used in thread safe manner? Feedback appreciated

      B Offline
      B Offline
      BillWoodruff
      wrote on last edited by
      #2

      I believe what you are after is the Singleton design-pattern. In addition to several articles on the Singleton design-pattern you can find here on CodeProject, there is a very useful analysis of different approaches by Jon Skeet (the C# uber-guru) here: [^] that covers issues of locking (thread safety), lazy initializtion, etc.

      «I want to stay as close to the edge as I can without going over. Out on the edge you see all kinds of things you can't see from the center» Kurt Vonnegut.

      L 1 Reply Last reply
      0
      • B BillWoodruff

        I believe what you are after is the Singleton design-pattern. In addition to several articles on the Singleton design-pattern you can find here on CodeProject, there is a very useful analysis of different approaches by Jon Skeet (the C# uber-guru) here: [^] that covers issues of locking (thread safety), lazy initializtion, etc.

        «I want to stay as close to the edge as I can without going over. Out on the edge you see all kinds of things you can't see from the center» Kurt Vonnegut.

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

        thank you but 1) you can see I am passing parameters to init method - those singletons on Jon Skeets article don't mention Singletons where you can pass parameters during init 2) I need a deinit method - users should be able to clear the Parameter class object, and set new properties if desired, again using method like init for example - since properties I have deliberately made read only 3) Can you show me sample how to achieve this using singleton?

        J 1 Reply Last reply
        0
        • L Lost User

          thank you but 1) you can see I am passing parameters to init method - those singletons on Jon Skeets article don't mention Singletons where you can pass parameters during init 2) I need a deinit method - users should be able to clear the Parameter class object, and set new properties if desired, again using method like init for example - since properties I have deliberately made read only 3) Can you show me sample how to achieve this using singleton?

          J Offline
          J Offline
          John Torjo
          wrote on last edited by
          #4

          Member 12061600 wrote:

          1. I need a deinit method - users should be able to clear the Parameter class object, and set new properties if desired, again using method like init for example - since properties I have deliberately made read only

          No you don't. At least, your deinit() does not need to be public anyway. When your init() method is called, you know if you're already initialized (thus, deinit() first, then re-init).

          Member 12061600 wrote:

          1. Can you show me sample how to achieve this using singleton?

          I'm sure you can figure it out on your own. That's how you learn ;P Best, John

          -- LogWizard - Log Viewing can be a joy!

          L 2 Replies Last reply
          0
          • J John Torjo

            Member 12061600 wrote:

            1. I need a deinit method - users should be able to clear the Parameter class object, and set new properties if desired, again using method like init for example - since properties I have deliberately made read only

            No you don't. At least, your deinit() does not need to be public anyway. When your init() method is called, you know if you're already initialized (thus, deinit() first, then re-init).

            Member 12061600 wrote:

            1. Can you show me sample how to achieve this using singleton?

            I'm sure you can figure it out on your own. That's how you learn ;P Best, John

            -- LogWizard - Log Viewing can be a joy!

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

            yeah but users of this class might need deinit to reinitialize the class

            J 1 Reply Last reply
            0
            • J John Torjo

              Member 12061600 wrote:

              1. I need a deinit method - users should be able to clear the Parameter class object, and set new properties if desired, again using method like init for example - since properties I have deliberately made read only

              No you don't. At least, your deinit() does not need to be public anyway. When your init() method is called, you know if you're already initialized (thus, deinit() first, then re-init).

              Member 12061600 wrote:

              1. Can you show me sample how to achieve this using singleton?

              I'm sure you can figure it out on your own. That's how you learn ;P Best, John

              -- LogWizard - Log Viewing can be a joy!

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

              does requirement to have public deinit make harder to make this class thread safe?

              1 Reply Last reply
              0
              • L Lost User

                yeah but users of this class might need deinit to reinitialize the class

                J Offline
                J Offline
                John Torjo
                wrote on last edited by
                #7

                I will reiterate: When your init() method is called, inside your init() function, you know if you're already initialized (thus, deinit() first, then re-init). Best, John

                -- LogWizard - Log Viewing can be a joy!

                L 1 Reply Last reply
                0
                • J John Torjo

                  I will reiterate: When your init() method is called, inside your init() function, you know if you're already initialized (thus, deinit() first, then re-init). Best, John

                  -- LogWizard - Log Viewing can be a joy!

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

                  deinit has to be public otherwise if someone calls init twice it will reinitialize automatically on second call - if I follow that approach you mention, is it thread safe?

                  J 1 Reply Last reply
                  0
                  • L Lost User

                    deinit has to be public otherwise if someone calls init twice it will reinitialize automatically on second call - if I follow that approach you mention, is it thread safe?

                    J Offline
                    J Offline
                    John Torjo
                    wrote on last edited by
                    #9

                    why?

                    -- LogWizard - Log Viewing can be a joy!

                    L 2 Replies Last reply
                    0
                    • J John Torjo

                      why?

                      -- LogWizard - Log Viewing can be a joy!

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

                      because that is how the class was used before that in C++ I am rewriting now Ok if I follow your suggestion then calling init twice - will reinitialize it yes? But is it thread safe now?

                      J 1 Reply Last reply
                      0
                      • J John Torjo

                        why?

                        -- LogWizard - Log Viewing can be a joy!

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

                        granted anyone using Parameters class WILL first check if it was inited or not using getter

                        1 Reply Last reply
                        0
                        • L Lost User

                          because that is how the class was used before that in C++ I am rewriting now Ok if I follow your suggestion then calling init twice - will reinitialize it yes? But is it thread safe now?

                          J Offline
                          J Offline
                          John Torjo
                          wrote on last edited by
                          #12

                          You really need to get a grasp on threading concepts. 1. Since you're accessing data inside a lock(), it is thread-safe 2. You can force the clients of your class to call init before using it - either with Debug.Asserts, or by throwing an exception if the class is not initalized 3. Why would you want to re-init this several times? Best, John

                          -- LogWizard - Log Viewing can be a joy!

                          L 1 Reply Last reply
                          0
                          • J John Torjo

                            You really need to get a grasp on threading concepts. 1. Since you're accessing data inside a lock(), it is thread-safe 2. You can force the clients of your class to call init before using it - either with Debug.Asserts, or by throwing an exception if the class is not initalized 3. Why would you want to re-init this several times? Best, John

                            -- LogWizard - Log Viewing can be a joy!

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

                            Few points: 1) I will make that class actually internal and only other class in DLL will be able to use it (I am writing that DLL too) - users can now use other public classes of DLL which use my Parameters class 2) So the only direct user of that class is ME and I can ensure before its properties are accessed by other methods in other classes, there is a call checking if the method is inited or not 3) Maybe users want to specify other parameters - hence need for deinit What do you think now?

                            J 1 Reply Last reply
                            0
                            • L Lost User

                              Few points: 1) I will make that class actually internal and only other class in DLL will be able to use it (I am writing that DLL too) - users can now use other public classes of DLL which use my Parameters class 2) So the only direct user of that class is ME and I can ensure before its properties are accessed by other methods in other classes, there is a call checking if the method is inited or not 3) Maybe users want to specify other parameters - hence need for deinit What do you think now?

                              J Offline
                              J Offline
                              John Torjo
                              wrote on last edited by
                              #14

                              3. you can provide a function (thread-safe) that changes the values (without de-initializing). Best, John

                              -- LogWizard - Log Viewing can be a joy!

                              L 1 Reply Last reply
                              0
                              • J John Torjo

                                3. you can provide a function (thread-safe) that changes the values (without de-initializing). Best, John

                                -- LogWizard - Log Viewing can be a joy!

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

                                Why are you so much against Deinit function? Is it so problematic? Assume I want Deinit function, I basically gave all the details in above comments and in the main question - would you say in such case my Parameters class is thread safe?

                                J 1 Reply Last reply
                                0
                                • L Lost User

                                  Why are you so much against Deinit function? Is it so problematic? Assume I want Deinit function, I basically gave all the details in above comments and in the main question - would you say in such case my Parameters class is thread safe?

                                  J Offline
                                  J Offline
                                  John Torjo
                                  wrote on last edited by
                                  #16

                                  1. About deinit()- if that's what you want, fine. It's just that to me it seems to just bring extra complexity - but hey, it's your code :) 2. Yes, it's thread-safe Best, John

                                  -- LogWizard - Log Viewing can be a joy!

                                  L 1 Reply Last reply
                                  0
                                  • J John Torjo

                                    1. About deinit()- if that's what you want, fine. It's just that to me it seems to just bring extra complexity - but hey, it's your code :) 2. Yes, it's thread-safe Best, John

                                    -- LogWizard - Log Viewing can be a joy!

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

                                    Is it also thread safe if I remove isInited checks from X1 and X2 getters? - Granted no one calls any methods of this class, unless a init method is called (this I can ensure because I am using this class directly) - I have isInited check first in any method calling this class.

                                    J 1 Reply Last reply
                                    0
                                    • L Lost User

                                      Is it also thread safe if I remove isInited checks from X1 and X2 getters? - Granted no one calls any methods of this class, unless a init method is called (this I can ensure because I am using this class directly) - I have isInited check first in any method calling this class.

                                      J Offline
                                      J Offline
                                      John Torjo
                                      wrote on last edited by
                                      #18

                                      1. Yes it is - variables X1/X2 are automatically initialized to zero. 2. You modified your code:

                                      public static int X1()
                                      {
                                      if(!isInited()) throw new Exception("init first");
                                      return x1;

                                      }

                                      should be

                                      public static int X1()
                                      {
                                      lock(this) {
                                      if(!isInited()) throw new Exception("init first");
                                      return x1;
                                      }
                                      }

                                      Best, John

                                      -- LogWizard - Log Viewing can be a joy!

                                      L 1 Reply Last reply
                                      0
                                      • J John Torjo

                                        1. Yes it is - variables X1/X2 are automatically initialized to zero. 2. You modified your code:

                                        public static int X1()
                                        {
                                        if(!isInited()) throw new Exception("init first");
                                        return x1;

                                        }

                                        should be

                                        public static int X1()
                                        {
                                        lock(this) {
                                        if(!isInited()) throw new Exception("init first");
                                        return x1;
                                        }
                                        }

                                        Best, John

                                        -- LogWizard - Log Viewing can be a joy!

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

                                        Yeah but I said what if I do

                                        public static int X1()
                                        {

                                          return x1;
                                        

                                        }

                                        Granted none calls these methods before INIT method is called (I can ensure this because I am writing those methods) - I will check isInited calls in the start of each method calling this class

                                        J 1 Reply Last reply
                                        0
                                        • L Lost User

                                          Yeah but I said what if I do

                                          public static int X1()
                                          {

                                            return x1;
                                          

                                          }

                                          Granted none calls these methods before INIT method is called (I can ensure this because I am writing those methods) - I will check isInited calls in the start of each method calling this class

                                          J Offline
                                          J Offline
                                          John Torjo
                                          wrote on last edited by
                                          #20

                                          No, that is not thread-safe. This is :

                                          public static int X1{} { lock(locker) return x1; }

                                          Best, John

                                          -- Romania is in mourning

                                          L 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