xref: /aoo42x/main/sal/inc/internal/once.h (revision 9eab2a37)
1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 #ifndef INCLUDED_SAL_INTERNAL_ONCE_H
25 #define INCLUDED_SAL_INTERNAL_ONCE_H
26 
27 /** sal_once_type
28  *  (platform dependent)
29  */
30 
31 #if defined(SAL_UNX) || defined(SAL_OS2)
32 
33 #include <pthread.h>
34 
35 typedef pthread_once_t sal_once_type;
36 
37 #define SAL_ONCE_INIT PTHREAD_ONCE_INIT
38 #define SAL_ONCE(once, init) pthread_once((once), (init))
39 
40 #elif defined(SAL_W32)
41 
42 #define WIN32_LEAN_AND_MEAN
43 #pragma warning(push,1) /* disable warnings within system headers */
44 #include <windows.h>
45 #pragma warning(pop)
46 
47 typedef struct sal_once_st sal_once_type;
48 struct sal_once_st
49 {
50 	LONG volatile m_done;
51 	LONG volatile m_lock;
52 };
53 
54 #define SAL_ONCE_INIT { 0, 0 }
55 #define SAL_ONCE(once, init) \
56 { \
57 	sal_once_type * control = (once); \
58 	if (!(control->m_done)) \
59 	{ \
60 		while (InterlockedExchange(&(control->m_lock), 1) == 1) Sleep(0); \
61 		if (!(control->m_done)) \
62 		{ \
63 			void (*init_routine)(void) = (init); \
64 			(*init_routine)(); \
65 			control->m_done = 1; \
66 		} \
67 		InterlockedExchange(&(control->m_lock), 0); \
68 	} \
69 }
70 
71 #else
72 #error Unknown platform
73 #endif /* SAL_UNX | SAL_W32 */
74 
75 #endif /* INCLUDED_SAL_INTERNAL_ONCE_H */
76