1 /*
2  * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
3  *
4  * SPDX-License-Identifier: MPL-2.0
5  *
6  * This Source Code Form is subject to the terms of the Mozilla Public
7  * License, v. 2.0.  If a copy of the MPL was not distributed with this
8  * file, you can obtain one at https://mozilla.org/MPL/2.0/.
9  *
10  * See the COPYRIGHT file distributed with this work for additional
11  * information regarding copyright ownership.
12  */
13 
14 #include <windows.h>
15 
16 #include <isc/assertions.h>
17 #include <isc/once.h>
18 #include <isc/util.h>
19 
20 isc_result_t
isc_once_do(isc_once_t * controller,void (* function)(void))21 isc_once_do(isc_once_t *controller, void (*function)(void)) {
22 	REQUIRE(controller != NULL && function != NULL);
23 
24 	if (controller->status == ISC_ONCE_INIT_NEEDED) {
25 		if (InterlockedDecrement(&controller->counter) == 0) {
26 			if (controller->status == ISC_ONCE_INIT_NEEDED) {
27 				function();
28 				controller->status = ISC_ONCE_INIT_DONE;
29 			}
30 		} else {
31 			while (controller->status == ISC_ONCE_INIT_NEEDED) {
32 				/*
33 				 * Sleep(0) indicates that this thread
34 				 * should be suspended to allow other
35 				 * waiting threads to execute.
36 				 */
37 				Sleep(0);
38 			}
39 		}
40 	}
41 
42 	return (ISC_R_SUCCESS);
43 }
44