brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 1 | /*----------------------------------------------------------------------------*/ |
| 2 | /* Copyright (c) FIRST 2008. All Rights Reserved. */ |
| 3 | /* Open Source Software - may be modified and shared by FRC teams. The code */ |
| 4 | /* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */ |
| 5 | /*----------------------------------------------------------------------------*/ |
| 6 | |
| 7 | #include "Synchronized.h" |
| 8 | |
| 9 | /** |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 10 | * Synchronized class deals with critical regions. |
| 11 | * Declare a Synchronized object at the beginning of a block. That will take the semaphore. |
| 12 | * When the code exits from the block it will call the destructor which will give the semaphore. |
| 13 | * This ensures that no matter how the block is exited, the semaphore will always be released. |
| 14 | * Use the CRITICAL_REGION(SEM_ID) and END_REGION macros to make the code look cleaner (see header file) |
| 15 | * @param semaphore The semaphore controlling this critical region. |
| 16 | */ |
| 17 | Synchronized::Synchronized(SEM_ID semaphore) |
| 18 | { |
| 19 | m_semaphore = semaphore; |
| 20 | semTake(m_semaphore, WAIT_FOREVER); |
| 21 | } |
brians | ab45cad | 2013-03-03 05:31:33 +0000 | [diff] [blame^] | 22 | |
| 23 | Synchronized::Synchronized(ReentrantSemaphore& semaphore) |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 24 | { |
brians | ab45cad | 2013-03-03 05:31:33 +0000 | [diff] [blame^] | 25 | m_semaphore = semaphore.m_semaphore; |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 26 | semTake(m_semaphore, WAIT_FOREVER); |
| 27 | } |
| 28 | |
| 29 | /** |
brians | ab45cad | 2013-03-03 05:31:33 +0000 | [diff] [blame^] | 30 | * This destructor unlocks the semaphore. |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 31 | */ |
| 32 | Synchronized::~Synchronized() |
| 33 | { |
| 34 | semGive(m_semaphore); |
| 35 | } |