1 /* Copyright 2016 Google Inc.
2 
3   Licensed under the Apache License, Version 2.0 (the "License");
4   you may not use this file except in compliance with the License.
5   You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9   Unless required by applicable law or agreed to in writing, software
10   distributed under the License is distributed on an "AS IS" BASIS,
11   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   See the License for the specific language governing permissions and
13   limitations under the License. */
14 
15 #include "headers.h"
16 
17 NSYNC_CPP_START_
18 
19 static pthread_key_t waiter_key;
20 static nsync_atomic_uint32_ pt_once;
21 
do_once(nsync_atomic_uint32_ * ponce,void (* dest)(void *))22 static void do_once (nsync_atomic_uint32_ *ponce, void (*dest) (void *)) {
23 	uint32_t o = ATM_LOAD_ACQ (ponce);
24 	if (o != 2) {
25 		while (o == 0 && !ATM_CAS_ACQ (ponce, 0, 1)) {
26 			o = ATM_LOAD (ponce);
27 		}
28 		if (o == 0) {
29 			pthread_key_create (&waiter_key, dest);
30 			ATM_STORE_REL (ponce, 2);
31 		}
32 		while (ATM_LOAD_ACQ (ponce) != 2) {
33 			sched_yield ();
34 		}
35 	}
36 }
37 
nsync_per_thread_waiter_(void (* dest)(void *))38 void *nsync_per_thread_waiter_ (void (*dest) (void *)) {
39 	do_once (&pt_once, dest);
40 	return (pthread_getspecific (waiter_key));
41 }
42 
nsync_set_per_thread_waiter_(void * v,void (* dest)(void *))43 void nsync_set_per_thread_waiter_ (void *v, void (*dest) (void *)) {
44 	do_once (&pt_once, dest);
45 	pthread_setspecific (waiter_key, v);
46 }
47 
48 NSYNC_CPP_END_
49