1 /*********************************************************************
2 
3     Implementation of common mutex operations
4 
5     Copyright:
6         Copyright (c) 2018 dunnhumby Germany GmbH.
7         All rights reserved.
8 
9     License:
10         Boost Software License Version 1.0. See LICENSE.txt for details.
11 
12 *********************************************************************/
13 
14 module ocean.util.aio.internal.MutexOps;
15 
16 import core.sys.posix.pthread;
17 import core.sys.posix.unistd;
18 import core.stdc.errno;
19 import ocean.sys.ErrnoException;
20 
21 /*********************************************************************
22 
23     Helper function to lock the mutex with the check for
24     the return value and throwing in the case of the error
25     This method must can be executed *ONLY* inside main thread.
26     Otherwise, GC holding glibc's mutex can deadlock, because
27     assert internally allocates memory from GC.
28 
29     Params:
30         mutex = pointer to the mutex handle
31         exception = ErrnoException instance to throw
32 
33 *********************************************************************/
34 
35 public void lock_mutex (pthread_mutex_t* mutex)
36 {
37     int ret = pthread_mutex_lock(mutex);
38 
39     switch (ret)
40     {
41         case 0:
42             break;
43         default:
44             throw (new ErrnoException).set(ret, "pthread_mutex_lock");
45         case EINVAL:
46             assert(false, "Mutex reference is invalid");
47         case EDEADLK:
48             assert(false, "The mutex is already locked by this thread");
49     }
50 }
51 
52 /*********************************************************************
53 
54     Helper function to unlock the mutex with the check for
55     the return value and throwing in the case of the error
56     This method must be executed *ONLY* inside main thread.
57     Otherwise, GC holding glibc's mutex can deadlock, because
58     assert internally allocates memory from GC.
59 
60     Params:
61         mutex = pointer to the mutex handle
62 
63 *********************************************************************/
64 
65 public void unlock_mutex (pthread_mutex_t* mutex)
66 {
67     int ret = pthread_mutex_unlock(mutex);
68 
69     switch (ret)
70     {
71         case 0:
72             break;
73         default:
74             throw (new ErrnoException).set(ret, "pthread_mutex_unlock");
75         case EINVAL:
76             assert(false, "Mutex reference is invalid");
77         case EPERM:
78             assert(false, "The calling thread does not own the mutex");
79     }
80 }