3 * Copyright 2015 gRPC authors.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
19 /* Win32 code for gpr synchronization support. */
21 #include <grpc/support/port_platform.h>
25 #include <grpc/support/log.h>
26 #include <grpc/support/sync.h>
27 #include <grpc/support/time.h>
29 void gpr_mu_init(gpr_mu* mu) {
30 InitializeCriticalSection(&mu->cs);
34 void gpr_mu_destroy(gpr_mu* mu) { DeleteCriticalSection(&mu->cs); }
36 void gpr_mu_lock(gpr_mu* mu) {
37 EnterCriticalSection(&mu->cs);
38 GPR_ASSERT(!mu->locked);
42 void gpr_mu_unlock(gpr_mu* mu) {
44 LeaveCriticalSection(&mu->cs);
47 int gpr_mu_trylock(gpr_mu* mu) {
48 int result = TryEnterCriticalSection(&mu->cs);
50 if (mu->locked) { /* This thread already holds the lock. */
51 LeaveCriticalSection(&mu->cs); /* Decrement lock count. */
52 result = 0; /* Indicate failure */
59 /*----------------------------------------*/
61 void gpr_cv_init(gpr_cv* cv) { InitializeConditionVariable(cv); }
63 void gpr_cv_destroy(gpr_cv* cv) {
64 /* Condition variables don't need destruction in Win32. */
67 int gpr_cv_wait(gpr_cv* cv, gpr_mu* mu, gpr_timespec abs_deadline) {
71 if (gpr_time_cmp(abs_deadline, gpr_inf_future(abs_deadline.clock_type)) ==
73 SleepConditionVariableCS(cv, &mu->cs, INFINITE);
75 abs_deadline = gpr_convert_clock_type(abs_deadline, GPR_CLOCK_REALTIME);
76 gpr_timespec now = gpr_now(abs_deadline.clock_type);
77 int64_t now_ms = (int64_t)now.tv_sec * 1000 + now.tv_nsec / 1000000;
79 (int64_t)abs_deadline.tv_sec * 1000 + abs_deadline.tv_nsec / 1000000;
80 if (now_ms >= deadline_ms) {
83 if ((deadline_ms - now_ms) >= INFINITE) {
84 timeout_max_ms = INFINITE - 1;
86 timeout_max_ms = (DWORD)(deadline_ms - now_ms);
88 timeout = (SleepConditionVariableCS(cv, &mu->cs, timeout_max_ms) == 0 &&
89 GetLastError() == ERROR_TIMEOUT);
96 void gpr_cv_signal(gpr_cv* cv) { WakeConditionVariable(cv); }
98 void gpr_cv_broadcast(gpr_cv* cv) { WakeAllConditionVariable(cv); }
100 /*----------------------------------------*/
103 struct run_once_func_arg {
104 void (*init_function)(void);
106 static BOOL CALLBACK run_once_func(gpr_once* once, void* v, void** pv) {
107 struct run_once_func_arg* arg = (struct run_once_func_arg*)v;
108 (*arg->init_function)();
112 void gpr_once_init(gpr_once* once, void (*init_function)(void)) {
113 struct run_once_func_arg arg;
114 arg.init_function = init_function;
115 InitOnceExecuteOnce(once, run_once_func, &arg, &dummy);
118 #endif /* GPR_WINDOWS */