1
2 /* This code implemented by Dag.Gruneau@elsa.preseco.comm.se */
3 /* Fast NonRecursiveMutex support by Yakov Markovitch, markovitch@iso.ru */
4 /* Eliminated some memory leaks, gsw@agere.com */
5
6 #include <windows.h>
7 #include <limits.h>
8 #ifdef HAVE_PROCESS_H
9 #include <process.h>
10 #endif
11
12 /* options */
13 #ifndef _PY_USE_CV_LOCKS
14 #define _PY_USE_CV_LOCKS 1 /* use locks based on cond vars */
15 #endif
16
17 /* Now, define a non-recursive mutex using either condition variables
18 * and critical sections (fast) or using operating system mutexes
19 * (slow)
20 */
21
22 #if _PY_USE_CV_LOCKS
23
24 #include "condvar.h"
25
26 typedef struct _NRMUTEX
27 {
28 PyMUTEX_T cs;
29 PyCOND_T cv;
30 int locked;
31 } NRMUTEX;
32 typedef NRMUTEX *PNRMUTEX;
33
34 PNRMUTEX
AllocNonRecursiveMutex()35 AllocNonRecursiveMutex()
36 {
37 PNRMUTEX m = (PNRMUTEX)PyMem_RawMalloc(sizeof(NRMUTEX));
38 if (!m)
39 return NULL;
40 if (PyCOND_INIT(&m->cv))
41 goto fail;
42 if (PyMUTEX_INIT(&m->cs)) {
43 PyCOND_FINI(&m->cv);
44 goto fail;
45 }
46 m->locked = 0;
47 return m;
48 fail:
49 PyMem_RawFree(m);
50 return NULL;
51 }
52
53 VOID
FreeNonRecursiveMutex(PNRMUTEX mutex)54 FreeNonRecursiveMutex(PNRMUTEX mutex)
55 {
56 if (mutex) {
57 PyCOND_FINI(&mutex->cv);
58 PyMUTEX_FINI(&mutex->cs);
59 PyMem_RawFree(mutex);
60 }
61 }
62
63 DWORD
EnterNonRecursiveMutex(PNRMUTEX mutex,DWORD milliseconds)64 EnterNonRecursiveMutex(PNRMUTEX mutex, DWORD milliseconds)
65 {
66 DWORD result = WAIT_OBJECT_0;
67 if (PyMUTEX_LOCK(&mutex->cs))
68 return WAIT_FAILED;
69 if (milliseconds == INFINITE) {
70 while (mutex->locked) {
71 if (PyCOND_WAIT(&mutex->cv, &mutex->cs)) {
72 result = WAIT_FAILED;
73 break;
74 }
75 }
76 } else if (milliseconds != 0) {
77 /* wait at least until the target */
78 DWORD now, target = GetTickCount() + milliseconds;
79 while (mutex->locked) {
80 if (PyCOND_TIMEDWAIT(&mutex->cv, &mutex->cs, (long long)milliseconds*1000) < 0) {
81 result = WAIT_FAILED;
82 break;
83 }
84 now = GetTickCount();
85 if (target <= now)
86 break;
87 milliseconds = target-now;
88 }
89 }
90 if (!mutex->locked) {
91 mutex->locked = 1;
92 result = WAIT_OBJECT_0;
93 } else if (result == WAIT_OBJECT_0)
94 result = WAIT_TIMEOUT;
95 /* else, it is WAIT_FAILED */
96 PyMUTEX_UNLOCK(&mutex->cs); /* must ignore result here */
97 return result;
98 }
99
100 BOOL
LeaveNonRecursiveMutex(PNRMUTEX mutex)101 LeaveNonRecursiveMutex(PNRMUTEX mutex)
102 {
103 BOOL result;
104 if (PyMUTEX_LOCK(&mutex->cs))
105 return FALSE;
106 mutex->locked = 0;
107 result = PyCOND_SIGNAL(&mutex->cv);
108 result &= PyMUTEX_UNLOCK(&mutex->cs);
109 return result;
110 }
111
112 #else /* if ! _PY_USE_CV_LOCKS */
113
114 /* NR-locks based on a kernel mutex */
115 #define PNRMUTEX HANDLE
116
117 PNRMUTEX
AllocNonRecursiveMutex()118 AllocNonRecursiveMutex()
119 {
120 return CreateSemaphore(NULL, 1, 1, NULL);
121 }
122
123 VOID
FreeNonRecursiveMutex(PNRMUTEX mutex)124 FreeNonRecursiveMutex(PNRMUTEX mutex)
125 {
126 /* No in-use check */
127 CloseHandle(mutex);
128 }
129
130 DWORD
EnterNonRecursiveMutex(PNRMUTEX mutex,DWORD milliseconds)131 EnterNonRecursiveMutex(PNRMUTEX mutex, DWORD milliseconds)
132 {
133 return WaitForSingleObjectEx(mutex, milliseconds, FALSE);
134 }
135
136 BOOL
LeaveNonRecursiveMutex(PNRMUTEX mutex)137 LeaveNonRecursiveMutex(PNRMUTEX mutex)
138 {
139 return ReleaseSemaphore(mutex, 1, NULL);
140 }
141 #endif /* _PY_USE_CV_LOCKS */
142
143 long PyThread_get_thread_ident(void);
144
145 /*
146 * Initialization of the C package, should not be needed.
147 */
148 static void
PyThread__init_thread(void)149 PyThread__init_thread(void)
150 {
151 }
152
153 /*
154 * Thread support.
155 */
156
157 typedef struct {
158 void (*func)(void*);
159 void *arg;
160 } callobj;
161
162 /* thunker to call adapt between the function type used by the system's
163 thread start function and the internally used one. */
164 static unsigned __stdcall
bootstrap(void * call)165 bootstrap(void *call)
166 {
167 callobj *obj = (callobj*)call;
168 void (*func)(void*) = obj->func;
169 void *arg = obj->arg;
170 HeapFree(GetProcessHeap(), 0, obj);
171 func(arg);
172 return 0;
173 }
174
175 long
PyThread_start_new_thread(void (* func)(void *),void * arg)176 PyThread_start_new_thread(void (*func)(void *), void *arg)
177 {
178 HANDLE hThread;
179 unsigned threadID;
180 callobj *obj;
181
182 dprintf(("%ld: PyThread_start_new_thread called\n",
183 PyThread_get_thread_ident()));
184 if (!initialized)
185 PyThread_init_thread();
186
187 obj = (callobj*)HeapAlloc(GetProcessHeap(), 0, sizeof(*obj));
188 if (!obj)
189 return -1;
190 obj->func = func;
191 obj->arg = arg;
192 hThread = (HANDLE)_beginthreadex(0,
193 Py_SAFE_DOWNCAST(_pythread_stacksize,
194 Py_ssize_t, unsigned int),
195 bootstrap, obj,
196 0, &threadID);
197 if (hThread == 0) {
198 /* I've seen errno == EAGAIN here, which means "there are
199 * too many threads".
200 */
201 int e = errno;
202 dprintf(("%ld: PyThread_start_new_thread failed, errno %d\n",
203 PyThread_get_thread_ident(), e));
204 threadID = (unsigned)-1;
205 HeapFree(GetProcessHeap(), 0, obj);
206 }
207 else {
208 dprintf(("%ld: PyThread_start_new_thread succeeded: %p\n",
209 PyThread_get_thread_ident(), (void*)hThread));
210 CloseHandle(hThread);
211 }
212 return (long) threadID;
213 }
214
215 /*
216 * Return the thread Id instead of a handle. The Id is said to uniquely identify the
217 * thread in the system
218 */
219 long
PyThread_get_thread_ident(void)220 PyThread_get_thread_ident(void)
221 {
222 if (!initialized)
223 PyThread_init_thread();
224
225 return GetCurrentThreadId();
226 }
227
228 void
PyThread_exit_thread(void)229 PyThread_exit_thread(void)
230 {
231 dprintf(("%ld: PyThread_exit_thread called\n", PyThread_get_thread_ident()));
232 if (!initialized)
233 exit(0);
234 _endthreadex(0);
235 }
236
237 /*
238 * Lock support. It has too be implemented as semaphores.
239 * I [Dag] tried to implement it with mutex but I could find a way to
240 * tell whether a thread already own the lock or not.
241 */
242 PyThread_type_lock
PyThread_allocate_lock(void)243 PyThread_allocate_lock(void)
244 {
245 PNRMUTEX aLock;
246
247 dprintf(("PyThread_allocate_lock called\n"));
248 if (!initialized)
249 PyThread_init_thread();
250
251 aLock = AllocNonRecursiveMutex() ;
252
253 dprintf(("%ld: PyThread_allocate_lock() -> %p\n", PyThread_get_thread_ident(), aLock));
254
255 return (PyThread_type_lock) aLock;
256 }
257
258 void
PyThread_free_lock(PyThread_type_lock aLock)259 PyThread_free_lock(PyThread_type_lock aLock)
260 {
261 dprintf(("%ld: PyThread_free_lock(%p) called\n", PyThread_get_thread_ident(),aLock));
262
263 FreeNonRecursiveMutex(aLock) ;
264 }
265
266 /*
267 * Return 1 on success if the lock was acquired
268 *
269 * and 0 if the lock was not acquired. This means a 0 is returned
270 * if the lock has already been acquired by this thread!
271 */
272 PyLockStatus
PyThread_acquire_lock_timed(PyThread_type_lock aLock,PY_TIMEOUT_T microseconds,int intr_flag)273 PyThread_acquire_lock_timed(PyThread_type_lock aLock,
274 PY_TIMEOUT_T microseconds, int intr_flag)
275 {
276 /* Fow now, intr_flag does nothing on Windows, and lock acquires are
277 * uninterruptible. */
278 PyLockStatus success;
279 PY_TIMEOUT_T milliseconds;
280
281 if (microseconds >= 0) {
282 milliseconds = microseconds / 1000;
283 if (microseconds % 1000 > 0)
284 ++milliseconds;
285 if ((DWORD) milliseconds != milliseconds)
286 Py_FatalError("Timeout too large for a DWORD, "
287 "please check PY_TIMEOUT_MAX");
288 }
289 else
290 milliseconds = INFINITE;
291
292 dprintf(("%ld: PyThread_acquire_lock_timed(%p, %lld) called\n",
293 PyThread_get_thread_ident(), aLock, microseconds));
294
295 if (aLock && EnterNonRecursiveMutex((PNRMUTEX)aLock,
296 (DWORD)milliseconds) == WAIT_OBJECT_0) {
297 success = PY_LOCK_ACQUIRED;
298 }
299 else {
300 success = PY_LOCK_FAILURE;
301 }
302
303 dprintf(("%ld: PyThread_acquire_lock(%p, %lld) -> %d\n",
304 PyThread_get_thread_ident(), aLock, microseconds, success));
305
306 return success;
307 }
308 int
PyThread_acquire_lock(PyThread_type_lock aLock,int waitflag)309 PyThread_acquire_lock(PyThread_type_lock aLock, int waitflag)
310 {
311 return PyThread_acquire_lock_timed(aLock, waitflag ? -1 : 0, 0);
312 }
313
314 void
PyThread_release_lock(PyThread_type_lock aLock)315 PyThread_release_lock(PyThread_type_lock aLock)
316 {
317 dprintf(("%ld: PyThread_release_lock(%p) called\n", PyThread_get_thread_ident(),aLock));
318
319 if (!(aLock && LeaveNonRecursiveMutex((PNRMUTEX) aLock)))
320 dprintf(("%ld: Could not PyThread_release_lock(%p) error: %ld\n", PyThread_get_thread_ident(), aLock, GetLastError()));
321 }
322
323 /* minimum/maximum thread stack sizes supported */
324 #define THREAD_MIN_STACKSIZE 0x8000 /* 32kB */
325 #define THREAD_MAX_STACKSIZE 0x10000000 /* 256MB */
326
327 /* set the thread stack size.
328 * Return 0 if size is valid, -1 otherwise.
329 */
330 static int
_pythread_nt_set_stacksize(size_t size)331 _pythread_nt_set_stacksize(size_t size)
332 {
333 /* set to default */
334 if (size == 0) {
335 _pythread_stacksize = 0;
336 return 0;
337 }
338
339 /* valid range? */
340 if (size >= THREAD_MIN_STACKSIZE && size < THREAD_MAX_STACKSIZE) {
341 _pythread_stacksize = size;
342 return 0;
343 }
344
345 return -1;
346 }
347
348 #define THREAD_SET_STACKSIZE(x) _pythread_nt_set_stacksize(x)
349
350
351 /* use native Windows TLS functions */
352 #define Py_HAVE_NATIVE_TLS
353
354 #ifdef Py_HAVE_NATIVE_TLS
355 int
PyThread_create_key(void)356 PyThread_create_key(void)
357 {
358 DWORD result= TlsAlloc();
359 if (result == TLS_OUT_OF_INDEXES)
360 return -1;
361 return (int)result;
362 }
363
364 void
PyThread_delete_key(int key)365 PyThread_delete_key(int key)
366 {
367 TlsFree(key);
368 }
369
370 int
PyThread_set_key_value(int key,void * value)371 PyThread_set_key_value(int key, void *value)
372 {
373 BOOL ok;
374
375 ok = TlsSetValue(key, value);
376 if (!ok)
377 return -1;
378 return 0;
379 }
380
381 void *
PyThread_get_key_value(int key)382 PyThread_get_key_value(int key)
383 {
384 /* because TLS is used in the Py_END_ALLOW_THREAD macro,
385 * it is necessary to preserve the windows error state, because
386 * it is assumed to be preserved across the call to the macro.
387 * Ideally, the macro should be fixed, but it is simpler to
388 * do it here.
389 */
390 DWORD error = GetLastError();
391 void *result = TlsGetValue(key);
392 SetLastError(error);
393 return result;
394 }
395
396 void
PyThread_delete_key_value(int key)397 PyThread_delete_key_value(int key)
398 {
399 /* NULL is used as "key missing", and it is also the default
400 * given by TlsGetValue() if nothing has been set yet.
401 */
402 TlsSetValue(key, NULL);
403 }
404
405 /* reinitialization of TLS is not necessary after fork when using
406 * the native TLS functions. And forking isn't supported on Windows either.
407 */
408 void
PyThread_ReInitTLS(void)409 PyThread_ReInitTLS(void)
410 {}
411
412 #endif
413