semaphore.cpp

Engine/source/platformWin32/threads/semaphore.cpp

More...

Classes:

Detailed Description

 1
 2//-----------------------------------------------------------------------------
 3// Copyright (c) 2012 GarageGames, LLC
 4//
 5// Permission is hereby granted, free of charge, to any person obtaining a copy
 6// of this software and associated documentation files (the "Software"), to
 7// deal in the Software without restriction, including without limitation the
 8// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 9// sell copies of the Software, and to permit persons to whom the Software is
10// furnished to do so, subject to the following conditions:
11//
12// The above copyright notice and this permission notice shall be included in
13// all copies or substantial portions of the Software.
14//
15// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21// IN THE SOFTWARE.
22//-----------------------------------------------------------------------------
23
24#include "platformWin32/platformWin32.h"
25#include "platform/threads/semaphore.h"
26
27class PlatformSemaphore
28{
29public:
30   HANDLE   *semaphore;
31
32   PlatformSemaphore(S32 initialCount)
33   {
34      semaphore = new HANDLE;
35      *semaphore = CreateSemaphore(0, initialCount, S32_MAX, 0);
36   }
37
38   ~PlatformSemaphore()
39   {
40      CloseHandle(*(HANDLE*)(semaphore));
41      delete semaphore;
42      semaphore = NULL;
43   }
44};
45
46Semaphore::Semaphore(S32 initialCount)
47{
48   mData = new PlatformSemaphore(initialCount);
49}
50
51Semaphore::~Semaphore()
52{
53   AssertFatal(mData && mData->semaphore, "Semaphore::destroySemaphore: invalid semaphore");
54   delete mData;
55}
56
57bool Semaphore::acquire(bool block, S32 timeoutMS)
58{
59   AssertFatal(mData && mData->semaphore, "Semaphore::acquireSemaphore: invalid semaphore");
60   if(block)
61   {
62      WaitForSingleObject(*(HANDLE*)(mData->semaphore), timeoutMS != -1 ? timeoutMS : INFINITE );
63      return(true);
64   }
65   else
66   {
67      DWORD result = WaitForSingleObject(*(HANDLE*)(mData->semaphore), 0);
68      return(result == WAIT_OBJECT_0);
69   }
70}
71
72void Semaphore::release()
73{
74   AssertFatal(mData && mData->semaphore, "Semaphore::releaseSemaphore: invalid semaphore");
75   ReleaseSemaphore(*(HANDLE*)(mData->semaphore), 1, 0);
76}
77