1 /* Plain mutexes (native Windows implementation).
2 Copyright (C) 2005-2024 Free Software Foundation, Inc.
4 This file is free software: you can redistribute it and/or modify
5 it under the terms of the GNU Lesser General Public License as
6 published by the Free Software Foundation; either version 2.1 of the
7 License, or (at your option) any later version.
9 This file is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 /* Written by Bruno Haible <bruno@clisp.org>, 2005.
18 Based on GCC's gthr-win32.h. */
23 #include "windows-mutex.h"
28 glwthread_mutex_init (glwthread_mutex_t
*mutex
)
30 InitializeCriticalSection (&mutex
->lock
);
31 mutex
->guard
.done
= 1;
35 glwthread_mutex_lock (glwthread_mutex_t
*mutex
)
37 if (!mutex
->guard
.done
)
39 if (InterlockedIncrement (&mutex
->guard
.started
) == 0)
40 /* This thread is the first one to need this mutex. Initialize it. */
41 glwthread_mutex_init (mutex
);
44 /* Don't let mutex->guard.started grow and wrap around. */
45 InterlockedDecrement (&mutex
->guard
.started
);
46 /* Yield the CPU while waiting for another thread to finish
47 initializing this mutex. */
48 while (!mutex
->guard
.done
)
52 EnterCriticalSection (&mutex
->lock
);
57 glwthread_mutex_trylock (glwthread_mutex_t
*mutex
)
59 if (!mutex
->guard
.done
)
61 if (InterlockedIncrement (&mutex
->guard
.started
) == 0)
62 /* This thread is the first one to need this mutex. Initialize it. */
63 glwthread_mutex_init (mutex
);
66 /* Don't let mutex->guard.started grow and wrap around. */
67 InterlockedDecrement (&mutex
->guard
.started
);
68 /* Let another thread finish initializing this mutex, and let it also
73 if (!TryEnterCriticalSection (&mutex
->lock
))
79 glwthread_mutex_unlock (glwthread_mutex_t
*mutex
)
81 if (!mutex
->guard
.done
)
83 LeaveCriticalSection (&mutex
->lock
);
88 glwthread_mutex_destroy (glwthread_mutex_t
*mutex
)
90 if (!mutex
->guard
.done
)
92 DeleteCriticalSection (&mutex
->lock
);
93 mutex
->guard
.done
= 0;