What happens if a thread is in the critical section or entering the critical section?











up vote
-1
down vote

favorite












I am trying to better understand a chapter and have been confused about what happens if a thread is in the critical section or is entering the critical section. May someone explain or give me an idea on the process of what the thread undergoes in such circumstances? Thank you.










share|improve this question


























    up vote
    -1
    down vote

    favorite












    I am trying to better understand a chapter and have been confused about what happens if a thread is in the critical section or is entering the critical section. May someone explain or give me an idea on the process of what the thread undergoes in such circumstances? Thank you.










    share|improve this question
























      up vote
      -1
      down vote

      favorite









      up vote
      -1
      down vote

      favorite











      I am trying to better understand a chapter and have been confused about what happens if a thread is in the critical section or is entering the critical section. May someone explain or give me an idea on the process of what the thread undergoes in such circumstances? Thank you.










      share|improve this question













      I am trying to better understand a chapter and have been confused about what happens if a thread is in the critical section or is entering the critical section. May someone explain or give me an idea on the process of what the thread undergoes in such circumstances? Thank you.







      operating-system thread-synchronization






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 11 at 0:06









      justoneday

      113




      113
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










          For an example, let's assume that you have an array, and multiple threads that read and write to the array; and if different threads are reading and writing to the array at the same time they'd see inconsistent data and it'd cause problems. To prevent those problems you protect the array with some kind of lock - before doing anything with the array a thread acquires the array's lock, and when it's finished using the array the thread releases the array's lock.



          For example:



              acquire_array_lock();
          /** Critical section (code that does something with the array) **/
          release_array_lock();


          There's nothing special about the code in the critical section. It does whatever it was designed to do (maybe sorting the array, maybe adding up all the numbers in the array, maybe displaying the array, etc) using code that's no different to code that you might use to do the same thing in a single-threaded system without locks.



          The only special parts are the code to acquire and release the lock.



          There are many types of locks (spinlocks, mutexes, semaphores), but they all have the same fundamental principle - when acquiring it you have something (e.g. a variable) to determine if a thread can/can't continue, then either (if the thread can't continue) some kind of waiting or (if the thread can continue) some kind of change to let others know they need to wait; and when releasing you have something to let others know they can stop waiting.



          The main difference between different kinds of locks is the implementation details - what kind of data is used to determine if a thread can/can't continue, and how a thread waits.



          For the simplest kind of lock (a spinlock) you might just have a single "yes/no" flag, a little bit like this (but not literally like this):



          acquire_lock(void) {
          while(myLock == 0) {
          // do nothing then retry
          }
          myLock = 1;
          }

          release_lock(void) {
          myLock = 0;
          }


          However this won't work because two or more threads can see that myLock == 0 at the same time and think they can both continue (and then do the myLock = 1 after it's too late). To fix this you need assembly language or special language support for atomic operations (e.g. a special function for "test and set" or "compare and exchange").



          The reason this is called a "spinlock" is that (if a thread needs to wait) it wastes CPU time continually checking ("spinning") to see if it can continue. Instead of doing this (to avoid wasting CPU time), a thread could tell a scheduler not to give it any CPU time until the lock is released; and this is how a mutex works.






          share|improve this answer





















          • thank you! But can the process holding the lock get context switched?
            – justoneday
            Nov 11 at 21:29










          • @justoneday: Whether a task holding a lock can get context switched depends on the environment. For normal tasks (threads, processes) on most operating systems a task can be context switched while holding a lock (otherwise there's a risk of malicious code deliberately acquiring a lock and never releasing it to hog all of the CPU time). For kernel code using spinlocks, typically context switches (and possibly IRQs too) are disabled to minimise the time that other CPUs will spend spinning.
            – Brendan
            Nov 12 at 3:57











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














           

          draft saved


          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53244644%2fwhat-happens-if-a-thread-is-in-the-critical-section-or-entering-the-critical-sec%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          0
          down vote



          accepted










          For an example, let's assume that you have an array, and multiple threads that read and write to the array; and if different threads are reading and writing to the array at the same time they'd see inconsistent data and it'd cause problems. To prevent those problems you protect the array with some kind of lock - before doing anything with the array a thread acquires the array's lock, and when it's finished using the array the thread releases the array's lock.



          For example:



              acquire_array_lock();
          /** Critical section (code that does something with the array) **/
          release_array_lock();


          There's nothing special about the code in the critical section. It does whatever it was designed to do (maybe sorting the array, maybe adding up all the numbers in the array, maybe displaying the array, etc) using code that's no different to code that you might use to do the same thing in a single-threaded system without locks.



          The only special parts are the code to acquire and release the lock.



          There are many types of locks (spinlocks, mutexes, semaphores), but they all have the same fundamental principle - when acquiring it you have something (e.g. a variable) to determine if a thread can/can't continue, then either (if the thread can't continue) some kind of waiting or (if the thread can continue) some kind of change to let others know they need to wait; and when releasing you have something to let others know they can stop waiting.



          The main difference between different kinds of locks is the implementation details - what kind of data is used to determine if a thread can/can't continue, and how a thread waits.



          For the simplest kind of lock (a spinlock) you might just have a single "yes/no" flag, a little bit like this (but not literally like this):



          acquire_lock(void) {
          while(myLock == 0) {
          // do nothing then retry
          }
          myLock = 1;
          }

          release_lock(void) {
          myLock = 0;
          }


          However this won't work because two or more threads can see that myLock == 0 at the same time and think they can both continue (and then do the myLock = 1 after it's too late). To fix this you need assembly language or special language support for atomic operations (e.g. a special function for "test and set" or "compare and exchange").



          The reason this is called a "spinlock" is that (if a thread needs to wait) it wastes CPU time continually checking ("spinning") to see if it can continue. Instead of doing this (to avoid wasting CPU time), a thread could tell a scheduler not to give it any CPU time until the lock is released; and this is how a mutex works.






          share|improve this answer





















          • thank you! But can the process holding the lock get context switched?
            – justoneday
            Nov 11 at 21:29










          • @justoneday: Whether a task holding a lock can get context switched depends on the environment. For normal tasks (threads, processes) on most operating systems a task can be context switched while holding a lock (otherwise there's a risk of malicious code deliberately acquiring a lock and never releasing it to hog all of the CPU time). For kernel code using spinlocks, typically context switches (and possibly IRQs too) are disabled to minimise the time that other CPUs will spend spinning.
            – Brendan
            Nov 12 at 3:57















          up vote
          0
          down vote



          accepted










          For an example, let's assume that you have an array, and multiple threads that read and write to the array; and if different threads are reading and writing to the array at the same time they'd see inconsistent data and it'd cause problems. To prevent those problems you protect the array with some kind of lock - before doing anything with the array a thread acquires the array's lock, and when it's finished using the array the thread releases the array's lock.



          For example:



              acquire_array_lock();
          /** Critical section (code that does something with the array) **/
          release_array_lock();


          There's nothing special about the code in the critical section. It does whatever it was designed to do (maybe sorting the array, maybe adding up all the numbers in the array, maybe displaying the array, etc) using code that's no different to code that you might use to do the same thing in a single-threaded system without locks.



          The only special parts are the code to acquire and release the lock.



          There are many types of locks (spinlocks, mutexes, semaphores), but they all have the same fundamental principle - when acquiring it you have something (e.g. a variable) to determine if a thread can/can't continue, then either (if the thread can't continue) some kind of waiting or (if the thread can continue) some kind of change to let others know they need to wait; and when releasing you have something to let others know they can stop waiting.



          The main difference between different kinds of locks is the implementation details - what kind of data is used to determine if a thread can/can't continue, and how a thread waits.



          For the simplest kind of lock (a spinlock) you might just have a single "yes/no" flag, a little bit like this (but not literally like this):



          acquire_lock(void) {
          while(myLock == 0) {
          // do nothing then retry
          }
          myLock = 1;
          }

          release_lock(void) {
          myLock = 0;
          }


          However this won't work because two or more threads can see that myLock == 0 at the same time and think they can both continue (and then do the myLock = 1 after it's too late). To fix this you need assembly language or special language support for atomic operations (e.g. a special function for "test and set" or "compare and exchange").



          The reason this is called a "spinlock" is that (if a thread needs to wait) it wastes CPU time continually checking ("spinning") to see if it can continue. Instead of doing this (to avoid wasting CPU time), a thread could tell a scheduler not to give it any CPU time until the lock is released; and this is how a mutex works.






          share|improve this answer





















          • thank you! But can the process holding the lock get context switched?
            – justoneday
            Nov 11 at 21:29










          • @justoneday: Whether a task holding a lock can get context switched depends on the environment. For normal tasks (threads, processes) on most operating systems a task can be context switched while holding a lock (otherwise there's a risk of malicious code deliberately acquiring a lock and never releasing it to hog all of the CPU time). For kernel code using spinlocks, typically context switches (and possibly IRQs too) are disabled to minimise the time that other CPUs will spend spinning.
            – Brendan
            Nov 12 at 3:57













          up vote
          0
          down vote



          accepted







          up vote
          0
          down vote



          accepted






          For an example, let's assume that you have an array, and multiple threads that read and write to the array; and if different threads are reading and writing to the array at the same time they'd see inconsistent data and it'd cause problems. To prevent those problems you protect the array with some kind of lock - before doing anything with the array a thread acquires the array's lock, and when it's finished using the array the thread releases the array's lock.



          For example:



              acquire_array_lock();
          /** Critical section (code that does something with the array) **/
          release_array_lock();


          There's nothing special about the code in the critical section. It does whatever it was designed to do (maybe sorting the array, maybe adding up all the numbers in the array, maybe displaying the array, etc) using code that's no different to code that you might use to do the same thing in a single-threaded system without locks.



          The only special parts are the code to acquire and release the lock.



          There are many types of locks (spinlocks, mutexes, semaphores), but they all have the same fundamental principle - when acquiring it you have something (e.g. a variable) to determine if a thread can/can't continue, then either (if the thread can't continue) some kind of waiting or (if the thread can continue) some kind of change to let others know they need to wait; and when releasing you have something to let others know they can stop waiting.



          The main difference between different kinds of locks is the implementation details - what kind of data is used to determine if a thread can/can't continue, and how a thread waits.



          For the simplest kind of lock (a spinlock) you might just have a single "yes/no" flag, a little bit like this (but not literally like this):



          acquire_lock(void) {
          while(myLock == 0) {
          // do nothing then retry
          }
          myLock = 1;
          }

          release_lock(void) {
          myLock = 0;
          }


          However this won't work because two or more threads can see that myLock == 0 at the same time and think they can both continue (and then do the myLock = 1 after it's too late). To fix this you need assembly language or special language support for atomic operations (e.g. a special function for "test and set" or "compare and exchange").



          The reason this is called a "spinlock" is that (if a thread needs to wait) it wastes CPU time continually checking ("spinning") to see if it can continue. Instead of doing this (to avoid wasting CPU time), a thread could tell a scheduler not to give it any CPU time until the lock is released; and this is how a mutex works.






          share|improve this answer












          For an example, let's assume that you have an array, and multiple threads that read and write to the array; and if different threads are reading and writing to the array at the same time they'd see inconsistent data and it'd cause problems. To prevent those problems you protect the array with some kind of lock - before doing anything with the array a thread acquires the array's lock, and when it's finished using the array the thread releases the array's lock.



          For example:



              acquire_array_lock();
          /** Critical section (code that does something with the array) **/
          release_array_lock();


          There's nothing special about the code in the critical section. It does whatever it was designed to do (maybe sorting the array, maybe adding up all the numbers in the array, maybe displaying the array, etc) using code that's no different to code that you might use to do the same thing in a single-threaded system without locks.



          The only special parts are the code to acquire and release the lock.



          There are many types of locks (spinlocks, mutexes, semaphores), but they all have the same fundamental principle - when acquiring it you have something (e.g. a variable) to determine if a thread can/can't continue, then either (if the thread can't continue) some kind of waiting or (if the thread can continue) some kind of change to let others know they need to wait; and when releasing you have something to let others know they can stop waiting.



          The main difference between different kinds of locks is the implementation details - what kind of data is used to determine if a thread can/can't continue, and how a thread waits.



          For the simplest kind of lock (a spinlock) you might just have a single "yes/no" flag, a little bit like this (but not literally like this):



          acquire_lock(void) {
          while(myLock == 0) {
          // do nothing then retry
          }
          myLock = 1;
          }

          release_lock(void) {
          myLock = 0;
          }


          However this won't work because two or more threads can see that myLock == 0 at the same time and think they can both continue (and then do the myLock = 1 after it's too late). To fix this you need assembly language or special language support for atomic operations (e.g. a special function for "test and set" or "compare and exchange").



          The reason this is called a "spinlock" is that (if a thread needs to wait) it wastes CPU time continually checking ("spinning") to see if it can continue. Instead of doing this (to avoid wasting CPU time), a thread could tell a scheduler not to give it any CPU time until the lock is released; and this is how a mutex works.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 11 at 4:10









          Brendan

          11.5k1230




          11.5k1230












          • thank you! But can the process holding the lock get context switched?
            – justoneday
            Nov 11 at 21:29










          • @justoneday: Whether a task holding a lock can get context switched depends on the environment. For normal tasks (threads, processes) on most operating systems a task can be context switched while holding a lock (otherwise there's a risk of malicious code deliberately acquiring a lock and never releasing it to hog all of the CPU time). For kernel code using spinlocks, typically context switches (and possibly IRQs too) are disabled to minimise the time that other CPUs will spend spinning.
            – Brendan
            Nov 12 at 3:57


















          • thank you! But can the process holding the lock get context switched?
            – justoneday
            Nov 11 at 21:29










          • @justoneday: Whether a task holding a lock can get context switched depends on the environment. For normal tasks (threads, processes) on most operating systems a task can be context switched while holding a lock (otherwise there's a risk of malicious code deliberately acquiring a lock and never releasing it to hog all of the CPU time). For kernel code using spinlocks, typically context switches (and possibly IRQs too) are disabled to minimise the time that other CPUs will spend spinning.
            – Brendan
            Nov 12 at 3:57
















          thank you! But can the process holding the lock get context switched?
          – justoneday
          Nov 11 at 21:29




          thank you! But can the process holding the lock get context switched?
          – justoneday
          Nov 11 at 21:29












          @justoneday: Whether a task holding a lock can get context switched depends on the environment. For normal tasks (threads, processes) on most operating systems a task can be context switched while holding a lock (otherwise there's a risk of malicious code deliberately acquiring a lock and never releasing it to hog all of the CPU time). For kernel code using spinlocks, typically context switches (and possibly IRQs too) are disabled to minimise the time that other CPUs will spend spinning.
          – Brendan
          Nov 12 at 3:57




          @justoneday: Whether a task holding a lock can get context switched depends on the environment. For normal tasks (threads, processes) on most operating systems a task can be context switched while holding a lock (otherwise there's a risk of malicious code deliberately acquiring a lock and never releasing it to hog all of the CPU time). For kernel code using spinlocks, typically context switches (and possibly IRQs too) are disabled to minimise the time that other CPUs will spend spinning.
          – Brendan
          Nov 12 at 3:57


















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53244644%2fwhat-happens-if-a-thread-is-in-the-critical-section-or-entering-the-critical-sec%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Florida Star v. B. J. F.

          Danny Elfman

          Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues