summaryrefslogtreecommitdiffstats
path: root/source/cSemaphore.cpp
blob: 96c542df6c40456f3de2e133f1d73e6e9dcf4aa9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include "cSemaphore.h"
#include "cMCLogger.h"

#ifdef _WIN32
#include <Windows.h>
#else
#include <semaphore.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#endif

cSemaphore::cSemaphore( unsigned int a_MaxCount, unsigned int a_InitialCount /* = 0 */ )
#ifndef _WIN32
    : m_bNamed( false )
#endif
{
#ifndef _WIN32
    (void)a_MaxCount;
    m_Handle = new sem_t;
    if( sem_init( (sem_t*)m_Handle, 0, 0 ) )
    {
        LOG("WARNING cSemaphore: Could not create unnamed semaphore, fallback to named.");
        delete (sem_t*)m_Handle;    // named semaphores return their own address
        m_bNamed = true;

        char c_Str[32];
        sprintf( c_Str, "cSemaphore%p", this );
        m_Handle = sem_open( c_Str, O_CREAT, 777, a_InitialCount );
        if( m_Handle == SEM_FAILED )
        {
            LOG("ERROR: Could not create Semaphore. (%i)", errno );
        }
        else
        {
            if( sem_unlink( c_Str ) != 0 )
            {
                LOG("ERROR: Could not unlink cSemaphore. (%i)", errno);
            }
        }
    }
#else
	m_Handle = CreateSemaphore(
		NULL, // security attribute
		a_InitialCount, // initial count
		a_MaxCount, // maximum count
		0 // name (optional)
		);
#endif
}

cSemaphore::~cSemaphore()
{
#ifdef _WIN32
	CloseHandle( m_Handle );
#else
    if( m_bNamed )
    {
        if( sem_close( (sem_t*)m_Handle ) != 0 )
        {
            LOG("ERROR: Could not close cSemaphore. (%i)", errno);
        }
    }
    else
    {
        sem_destroy( (sem_t*)m_Handle );
        delete (sem_t*)m_Handle;
    }
	m_Handle = 0;

#endif
}

void cSemaphore::Wait()
{
#ifndef _WIN32
    if( sem_wait( (sem_t*)m_Handle ) != 0)
    {
        LOG("ERROR: Could not wait for cSemaphore. (%i)", errno);
    }
#else
	WaitForSingleObject( m_Handle, INFINITE);
#endif
}

void cSemaphore::Signal()
{
#ifndef _WIN32
	if( sem_post( (sem_t*)m_Handle ) != 0 )
	{
        LOG("ERROR: Could not signal cSemaphore. (%i)", errno);
	}
#else
	ReleaseSemaphore( m_Handle, 1, NULL );
#endif
}