James Kuszmaul | 82f6c04 | 2021-01-17 11:30:16 -0800 | [diff] [blame^] | 1 | /** |
| 2 | * @file win32/lock.c Locking for Windows |
| 3 | * |
| 4 | * Copyright (C) 2010 Creytiv.com |
| 5 | */ |
| 6 | #undef _WIN32_WINNT |
| 7 | #define _WIN32_WINNT 0x0400 |
| 8 | #include <windows.h> |
| 9 | #include <re_types.h> |
| 10 | #include <re_mem.h> |
| 11 | #include <re_lock.h> |
| 12 | |
| 13 | |
| 14 | struct lock { |
| 15 | CRITICAL_SECTION c; |
| 16 | }; |
| 17 | |
| 18 | |
| 19 | static void lock_destructor(void *data) |
| 20 | { |
| 21 | struct lock *l = data; |
| 22 | |
| 23 | DeleteCriticalSection(&l->c); |
| 24 | } |
| 25 | |
| 26 | |
| 27 | int lock_alloc(struct lock **lp) |
| 28 | { |
| 29 | struct lock *l; |
| 30 | |
| 31 | if (!lp) |
| 32 | return EINVAL; |
| 33 | |
| 34 | l = mem_alloc(sizeof(*l), lock_destructor); |
| 35 | if (!l) |
| 36 | return ENOMEM; |
| 37 | |
| 38 | InitializeCriticalSection(&l->c); |
| 39 | |
| 40 | *lp = l; |
| 41 | return 0; |
| 42 | } |
| 43 | |
| 44 | |
| 45 | void lock_read_get(struct lock *l) |
| 46 | { |
| 47 | EnterCriticalSection(&l->c); |
| 48 | } |
| 49 | |
| 50 | |
| 51 | void lock_write_get(struct lock *l) |
| 52 | { |
| 53 | EnterCriticalSection(&l->c); |
| 54 | } |
| 55 | |
| 56 | |
| 57 | int lock_read_try(struct lock *l) |
| 58 | { |
| 59 | return TryEnterCriticalSection(&l->c) ? 0 : ENODEV; |
| 60 | } |
| 61 | |
| 62 | |
| 63 | int lock_write_try(struct lock *l) |
| 64 | { |
| 65 | return TryEnterCriticalSection(&l->c) ? 0 : ENODEV; |
| 66 | } |
| 67 | |
| 68 | |
| 69 | void lock_rel(struct lock *l) |
| 70 | { |
| 71 | LeaveCriticalSection(&l->c); |
| 72 | } |