Advertisement
princeofisles

Critical Section

Nov 16th, 2014
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. /*
  2. In concurrent programming, a critical section is a piece of code that accesses a shared resource (data structure or device) that must not be concurrently accessed by more than one thread of execution.[1] A critical section will usually terminate in fixed time, and a thread, task, or process will have to wait for a fixed time to enter it (aka bounded waiting). Some synchronization mechanism is required at the entry and exit of the critical section to ensure exclusive use, for example a semaphore.
  3. */
  4. /* Sample C/C++, Windows, link to kernel32.dll */
  5. #include <windows.h>
  6.  
  7. static CRITICAL_SECTION cs; /* This is the critical section object -- once initialized,
  8.                                it cannot be moved in memory */
  9.                             /* If you program in OOP, declare this as a non-static member in your class */
  10. void f()
  11. {
  12.     /* Enter the critical section -- other threads are locked out */
  13.     EnterCriticalSection(&cs);
  14.  
  15.     /* Do some thread-safe processing! */
  16.  
  17.     /* Leave the critical section -- other threads can now EnterCriticalSection() */
  18.     LeaveCriticalSection(&cs);
  19. }
  20.  
  21. int main()
  22. {
  23.     /* Initialize the critical section before entering multi-threaded context. */
  24.     InitializeCriticalSection(&cs);
  25.  
  26.     f();
  27.  
  28.     /* Release system object when all finished -- usually at the end of the cleanup code */
  29.     DeleteCriticalSection(&cs);
  30. return 0;
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement