File: locking.cpp

package info (click to toggle)
polyml 5.6-8
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 31,892 kB
  • ctags: 34,453
  • sloc: cpp: 44,983; ansic: 24,520; asm: 14,850; sh: 11,730; makefile: 551; exp: 484; python: 253; awk: 91; sed: 9
file content (329 lines) | stat: -rw-r--r-- 8,710 bytes parent folder | download | duplicates (4)
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
/*
    Title:      Mutex and Condition Variable library.

    Copyright (c) 2007, 2012, 2015 David C. J. Matthews

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License version 2.1 as published by the Free Software Foundation.
    
    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.
    
    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

*/

#ifdef HAVE_CONFIG_H
#include "config.h"
#elif defined(_WIN32)
#include "winconfig.h"
#else
#error "No configuration file"
#endif

#if ((!defined(_WIN32) || defined(__CYGWIN__)) && defined(HAVE_PTHREAD_H))
#define HAVE_PTHREAD 1
#include <pthread.h>
#elif (defined(HAVE_WINDOWS_H))
#include <windows.h>
#endif

#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif

#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif

#ifdef HAVE_TIME_H
#include <time.h>
#endif

#if ((!defined(_WIN32) || defined(__CYGWIN__)) && defined(HAVE_SEMAPHORE_H))
// Don't include semaphore.h on Mingw.  It's provided but doesn't compile.
#include <semaphore.h>
#endif

#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif

#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif

#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

#ifdef HAVE_STDIO_H
#include <stdio.h>
#endif

#include "locking.h"
#include "diagnostics.h"

// Report contended locks after this many attempts
#define LOCK_REPORT_COUNT   50

PLock::PLock(const char *n): lockName(n), lockCount(0)
{
#ifdef HAVE_PTHREAD
    pthread_mutex_init(&lock, 0);
#elif defined(HAVE_WINDOWS_H)
    InitializeCriticalSection(&lock);
#endif
}

PLock::~PLock()
{
#ifdef HAVE_PTHREAD
    pthread_mutex_destroy(&lock);
#elif defined(HAVE_WINDOWS_H)
    DeleteCriticalSection(&lock);
#endif
}

void PLock::Lock(void)
{
#if (defined(HAVE_PTHREAD) || defined(HAVE_WINDOWS_H))
    if (debugOptions & DEBUG_CONTENTION)
    {
        // Report a heavily contended lock.
        if (Trylock())
            return;
        if (++lockCount > LOCK_REPORT_COUNT)
        {
            if (lockName != 0)
                Log("Lock: contention on lock: %s\n", lockName);
            else
                Log("Lock: contention on lock at %p\n", &lock);
            lockCount = 0;
        }
        // Drop through to a normal lock
    }
#endif
#ifdef HAVE_PTHREAD
    pthread_mutex_lock(&lock);
#elif defined(HAVE_WINDOWS_H)
    EnterCriticalSection(&lock);
#endif
    // If we don't support threads this does nothing.
}

void PLock::Unlock(void)
{
#ifdef HAVE_PTHREAD
    pthread_mutex_unlock(&lock);
#elif defined(HAVE_WINDOWS_H)
    LeaveCriticalSection(&lock);
#endif
}

bool PLock::Trylock(void)
{
#ifdef HAVE_PTHREAD
    // Since we use normal mutexes this returns EBUSY if the
    // current thread owns the mutex.
    return pthread_mutex_trylock(&lock) != EBUSY;
#elif defined(HAVE_WINDOWS_H)
    // This is not implemented properly in Windows.  There is
    // TryEnterCriticalSection in Win NT and later but that
    // returns TRUE if the current thread owns the mutex.
   return TryEnterCriticalSection(&lock) == TRUE;
#else
   return true; // Single-threaded.
#endif
}

PCondVar::PCondVar()
{
#ifdef HAVE_PTHREAD
    pthread_cond_init(&cond, NULL);
#elif defined(HAVE_WINDOWS_H)
    InitializeConditionVariable(&cond);
#endif
}

PCondVar::~PCondVar()
{
#ifdef HAVE_PTHREAD
    pthread_cond_destroy(&cond);
#endif
}

// Wait indefinitely.  Drops the lock and reaquires it.
void PCondVar::Wait(PLock *pLock)
{
#ifdef HAVE_PTHREAD
    pthread_cond_wait(&cond, &pLock->lock);
#elif defined(HAVE_WINDOWS_H)
    SleepConditionVariableCS(&cond, &pLock->lock, INFINITE);
#endif
}

// Wait until a specified absolute time.  Drops the lock and reaquires it.
#if (defined(_WIN32) && ! defined(__CYGWIN__))
// Windows with Windows-style times
void PCondVar::WaitUntil(PLock *pLock, const FILETIME *time)
{
    FILETIME now;
    GetSystemTimeAsFileTime(&now);
    LARGE_INTEGER liNow, liTime;
    liNow.HighPart = now.dwHighDateTime;
    liNow.LowPart = now.dwLowDateTime;
    liTime.HighPart = time->dwHighDateTime;
    liTime.LowPart = time->dwLowDateTime;
    if (liNow.QuadPart >= liTime.QuadPart) // Already past the time
        return;
    DWORD toWait = (DWORD)((liTime.QuadPart - liNow.QuadPart) / (LONGLONG)10000);
    (void)WaitFor(pLock, toWait);
}
#else
// Unix-style times
void PCondVar::WaitUntil(PLock *pLock, const timespec *time)
{
#ifdef HAVE_PTHREAD
    pthread_cond_timedwait(&cond, &pLock->lock, time);
#elif defined(HAVE_WINDOWS_H)
    // This must be Cygwin but compiled with --without-threads
    struct timeval tv;
    if (gettimeofday(&tv, NULL) != 0)
        return;
    if (tv.tv_sec > time->tv_sec || (tv.tv_sec == time->tv_sec && tv.tv_usec >= time->tv_nsec/1000))
        return; // Already past the time
    WaitFor(pLock, (time->tv_sec - tv.tv_sec) * 1000 + time->tv_nsec/1000000 - tv.tv_usec/1000);
#endif
}
#endif

// Wait for a number of milliseconds.  Used within the RTS.  Drops the lock and reaquires it.
// Returns true if the return was because the condition variable had been signalled.
// Returns false if the timeout expired or there was an error.
bool PCondVar::WaitFor(PLock *pLock, unsigned milliseconds)
{
#ifdef HAVE_PTHREAD
    struct timespec waitTime;
    struct timeval tv;
    if (gettimeofday(&tv, NULL) != 0)
        return false;
    waitTime.tv_sec = tv.tv_sec + milliseconds / 1000;
    waitTime.tv_nsec = (tv.tv_usec + (milliseconds % 1000) * 1000) * 1000;
    if (waitTime.tv_nsec >= 1000*1000*1000)
    {
        waitTime.tv_nsec -= 1000*1000*1000;
        waitTime.tv_sec += 1;
    }
    return pthread_cond_timedwait(&cond, &pLock->lock, &waitTime) == 0;
#elif defined(HAVE_WINDOWS_H)
    // SleepConditionVariableCS returns zero on error or timeout.
    return SleepConditionVariableCS(&cond, &pLock->lock, milliseconds) != 0;
#else
    return true; // Single-threaded.  Return immediately.
#endif
}

// Wake up all the waiting threads. 
void PCondVar::Signal(void)
{
#ifdef HAVE_PTHREAD
    pthread_cond_broadcast(&cond);
#elif defined(HAVE_WINDOWS_H)
    WakeAllConditionVariable(&cond);
#endif
}


// Initialise a semphore.  Tries to create an unnamed semaphore if
// it can but tries a named semaphore if it can't.  Mac OS X only
// supports named semaphores.
// The semaphore is initialised with a count of zero.
PSemaphore::PSemaphore()
{
#if ((!defined(_WIN32) || defined(__CYGWIN__)) && defined(HAVE_SEMAPHORE_H))
    sema = 0;
    isLocal = true;
#elif defined(HAVE_WINDOWS_H)
    sema = NULL;
#endif
}

PSemaphore::~PSemaphore()
{
#if ((!defined(_WIN32) || defined(__CYGWIN__)) && defined(HAVE_SEMAPHORE_H))
    if (sema && isLocal) sem_destroy(sema);
    else if (sema && !isLocal) sem_close(sema);
#elif defined(HAVE_WINDOWS_H)
    if (sema != NULL) CloseHandle(sema);
#endif
}

bool PSemaphore::Init(unsigned init, unsigned max)
{
#if ((!defined(_WIN32) || defined(__CYGWIN__)) && defined(HAVE_SEMAPHORE_H))
    isLocal = true;
    if (sem_init(&localSema, 0, init) == 0) {
        sema = &localSema;
        return true;
    }
#if (defined(__CYGWIN__))
    // Cygwin doesn't define sem_unlink but that doesn't matter
    // since sem_init works.
    sema = 0;
    return false;
#else
    isLocal = false;
    char semname[30];
    static int count=0;
    sprintf(semname, "poly%0d-%0d", (int)getpid(), count++);
    sema = sem_open(semname, O_CREAT|O_EXCL, 00666, init);
    if (sema == (sem_t*)SEM_FAILED) {
        sema = 0;
        return false;
    }
    sem_unlink(semname);
    return true;
#endif
#elif defined(HAVE_WINDOWS_H)
    sema = CreateSemaphore(NULL, init, max, NULL);
    return sema != NULL;
#endif
}

bool PSemaphore::Wait(void)
{
#if ((!defined(_WIN32) || defined(__CYGWIN__)) && defined(HAVE_SEMAPHORE_H))
    // Wait until the semaphore is signalled.  A Unix signal may interrupt
    // it so we need to retry in that case.
    while (sem_wait(sema) == -1)
    {
        if (errno != EINTR)
            return false;
    }
    return true;
#elif defined(HAVE_WINDOWS_H)
    return WaitForSingleObject(sema, INFINITE) == WAIT_OBJECT_0;
#endif
}

void PSemaphore::Signal(void)
{
#if ((!defined(_WIN32) || defined(__CYGWIN__)) && defined(HAVE_SEMAPHORE_H))
    sem_post(sema);
#elif defined(HAVE_WINDOWS_H)
    ReleaseSemaphore(sema, 1, NULL);
#endif
}