Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 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.
- */
- /* Sample C/C++, Windows, link to kernel32.dll */
- #include <windows.h>
- static CRITICAL_SECTION cs; /* This is the critical section object -- once initialized,
- it cannot be moved in memory */
- /* If you program in OOP, declare this as a non-static member in your class */
- void f()
- {
- /* Enter the critical section -- other threads are locked out */
- EnterCriticalSection(&cs);
- /* Do some thread-safe processing! */
- /* Leave the critical section -- other threads can now EnterCriticalSection() */
- LeaveCriticalSection(&cs);
- }
- int main()
- {
- /* Initialize the critical section before entering multi-threaded context. */
- InitializeCriticalSection(&cs);
- f();
- /* Release system object when all finished -- usually at the end of the cleanup code */
- DeleteCriticalSection(&cs);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement