Debian Codegraph @

include/plink2_thread.h

raw
1 #ifndef __PLINK2_THREAD_H__
2 #define __PLINK2_THREAD_H__
3
4 // This library is part of PLINK 2.0, copyright (C) 2005-2025 Shaun Purcell,
5 // Christopher Chang.
6 //
7 // This program is free software: you can redistribute it and/or modify it
8 // under the terms of the GNU Lesser General Public License as published by the
9 // Free Software Foundation, either version 3 of the License, or (at your
10 // option) any later version.
11 //
12 // This library is distributed in the hope that it will be useful, but WITHOUT
13 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
15 // for more details.
16 //
17 // You should have received a copy of the GNU Lesser General Public License
18 // along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20
21 // Basic multithreading code. Uses native Win32 API instead of pthreads
22 // emulation on Windows.
23 // Probable todo: decent scheduling. plink2_bgzf currently has bespoke
24 // sequential-scheduling logic that's more efficient than what the rest of
25 // plink2 is doing; that's probably worth generalizing. In the non-sequential
26 // case (where e.g. an entire block of 2^16 variants is processed at once, and
27 // beyond some locality-associated efficiency benefits it doesn't matter what
28 // order the variants within the block are handled in), work-stealing or
29 // something with a similar effect should be implemented.
30 #include "plink2_base.h"
31
32 #ifdef _WIN32
33 # include <process.h>
34 #else
35 # include <pthread.h>
36 #endif
37
38 // Most thread functions should be of the form
39 // THREAD_FUNC_DECL function_name(void* raw_arg) {
40 // ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
41 // uint32_t tidx = arg->tidx;
42 // ...
43 // do {
44 // ... // process current block
45 // } while (!THREAD_BLOCK_FINISH(arg));
46 // THREAD_RETURN;
47 // }
48 // or
49 // THREAD_FUNC_DECL function_name(void* raw_arg) {
50 // ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
51 // uint32_t tidx = arg->tidx;
52 // ...
53 // // parallelized initialization code, must wait for other threads to also
54 // // finish this before proceeding to main loop
55 // while (!THREAD_BLOCK_FINISH(arg)) {
56 // ... // process current block
57 // }
58 // THREAD_RETURN;
59 // }
60 #ifdef _WIN32
61 # define pthread_t HANDLE
62 # define THREAD_FUNC_DECL unsigned __stdcall
63 # define THREAD_FUNCPTR_T(func_ptr) unsigned (__stdcall *func_ptr)(void*)
64 // #define THREAD_FUNCPP_T(func_pp) unsigned (__stdcall **func_pp)(void*)
65 # define THREAD_RETURN return 0
66 #else
67 # define THREAD_FUNC_DECL void*
68 # define THREAD_FUNCPTR_T(func_ptr) void* (*func_ptr)(void*)
69 // #define THREAD_FUNCPP_T(func_pp) void* (**func_pp)(void*)
70 # define THREAD_RETURN return nullptr
71 #endif
72
73 #if (__GNUC__ == 4) && (__GNUC_MINOR__ < 7) && !defined(__clang__)
74 // todo: check if this is also needed for any clang versions we care about.
75 // (support was added in clang 3.1, I think?)
76 # define __ATOMIC_RELAXED 0
77 # define __ATOMIC_CONSUME 1
78 # define __ATOMIC_ACQUIRE 2
79 # define __ATOMIC_RELEASE 3
80 # define __ATOMIC_ACQ_REL 4
81 # define __ATOMIC_SEQ_CST 5
82 # define __atomic_fetch_add(ptr, val, memorder) __sync_fetch_and_add((ptr), (val))
83 # define __atomic_fetch_sub(ptr, val, memorder) __sync_fetch_and_sub((ptr), (val))
84 # define __atomic_sub_fetch(ptr, val, memorder) __sync_sub_and_fetch((ptr), (val))
85
86 HEADER_INLINE uint32_t ATOMIC_COMPARE_EXCHANGE_N_U32(uint32_t* ptr, uint32_t* expected, uint32_t desired, __maybe_unused int weak, __maybe_unused int success_memorder, __maybe_unused int failure_memorder) {
87 const uint32_t new_expected = __sync_val_compare_and_swap(ptr, *expected, desired);
88 if (new_expected == (*expected)) {
89 return 1;
90 }
91 *expected = new_expected;
92 return 0;
93 }
94
95 HEADER_INLINE uint32_t ATOMIC_COMPARE_EXCHANGE_N_U64(uint64_t* ptr, uint64_t* expected, uint64_t desired, __maybe_unused int weak, __maybe_unused int success_memorder, __maybe_unused int failure_memorder) {
96 const uint64_t new_expected = __sync_val_compare_and_swap(ptr, *expected, desired);
97 if (new_expected == (*expected)) {
98 return 1;
99 }
100 *expected = new_expected;
101 return 0;
102 }
103 #else
104 # define ATOMIC_COMPARE_EXCHANGE_N_U32 __atomic_compare_exchange_n
105 # define ATOMIC_COMPARE_EXCHANGE_N_U64 __atomic_compare_exchange_n
106 #endif
107
108 #ifdef __cplusplus
109 namespace plink2 {
110 #endif
111
112 extern const char kErrstrThreadCreate[];
113
114 #ifdef _WIN32
115 void WaitForAllObjects(uint32_t ct, HANDLE* objs);
116 #endif
117
118 #ifdef _WIN32
119 // This should be increased once the old-style threads code has been purged.
120 CONSTI32(kMaxThreads, 64);
121 #else
122 // currently assumed to be less than 2^16 (otherwise some multiply overflows
123 // are theoretically possible, at least in the 32-bit build)
124 CONSTI32(kMaxThreads, 512);
125 #endif
126
127 #ifdef __APPLE__
128 // cblas_dgemm may fail with 128k
129 CONSTI32(kDefaultThreadStack, 524288);
130 #else
131 // asserts didn't seem to work properly with a setting much smaller than this
132 CONSTI32(kDefaultThreadStack, 131072);
133 #endif
134
135 typedef struct ThreadGroupControlBlockStruct {
136 // Neither thread-functions nor the thread-group owner should touch these
137 // variables directly.
138 uintptr_t spawn_ct;
139 #ifdef _WIN32
140 HANDLE start_next_events[2]; // uses parity of spawn_ct
141 HANDLE cur_block_done_event;
142 #else
143 pthread_mutex_t sync_mutex;
144 pthread_cond_t cur_block_done_condvar;
145 pthread_cond_t start_next_condvar;
146 #endif
147 uint32_t active_ct;
148
149 // Thread-functions can safely read from these.
150 uint32_t thread_ct;
151
152 // 1 = process last block and exit; 2 = immediate termination requested
153 uint32_t is_last_block;
154 } ThreadGroupControlBlock;
155
156 typedef struct ThreadGroupSharedStruct {
157 void* context;
158 #ifdef __cplusplus
159 ThreadGroupControlBlock& GET_PRIVATE_cb() { return cb; }
160 ThreadGroupControlBlock const& GET_PRIVATE_cb() const { return cb; }
161 private:
162 #endif
163 ThreadGroupControlBlock cb;
164 } ThreadGroupShared;
165
166 typedef struct ThreadGroupFuncArgStruct {
167 ThreadGroupShared* sharedp;
168 uint32_t tidx;
169 } ThreadGroupFuncArg;
170
171 typedef struct ThreadGroupMainStruct {
172 ThreadGroupShared shared;
173 THREAD_FUNCPTR_T(thread_func_ptr);
174 pthread_t* threads;
175 ThreadGroupFuncArg* thread_args;
176 // Generally favor uint16_t/uint32_t over unsigned char/uint8_t for isolated
177 // bools, since in the latter case the compiler is fairly likely to generate
178 // worse code due to aliasing paranoia; see e.g.
179 // https://travisdowns.github.io/blog/2019/08/26/vector-inc.html
180 uint16_t is_unjoined;
181 uint16_t is_active;
182
183 #ifndef _WIN32
184 uint32_t sync_init_state;
185 #endif
186 } ThreadGroupMain;
187
188 typedef struct ThreadGroupStruct {
189 #ifdef __cplusplus
190 ThreadGroupMain& GET_PRIVATE_m() { return m; }
191 ThreadGroupMain const& GET_PRIVATE_m() const { return m; }
192 private:
193 #endif
194 ThreadGroupMain m;
195 } ThreadGroup;
196
197 void PreinitThreads(ThreadGroup* tg_ptr);
198
199 // Return value is clipped to 1..kMaxThreads.
200 // If known_procs_ptr is non-null, it's set to the raw unclipped value (which
201 // can theoretically be -1 if the sysconf call fails)
202 uint32_t NumCpu(int32_t* known_procs_ptr);
203
204 // Also allocates, returning 1 on failure.
205 BoolErr SetThreadCt(uint32_t thread_ct, ThreadGroup* tg_ptr);
206
207 HEADER_INLINE uint32_t GetThreadCt(const ThreadGroupShared* sharedp) {
208 return GET_PRIVATE(*sharedp, cb).thread_ct;
209 }
210
211 HEADER_INLINE uint32_t GetThreadCtTg(const ThreadGroup* tg_ptr) {
212 const ThreadGroupMain* tgp = &GET_PRIVATE(*tg_ptr, m);
213 return GET_PRIVATE(tgp->shared, cb).thread_ct;
214 }
215
216 HEADER_INLINE void SetThreadFuncAndData(THREAD_FUNCPTR_T(start_routine), void* shared_context, ThreadGroup* tg_ptr) {
217 ThreadGroupMain* tgp = &GET_PRIVATE(*tg_ptr, m);
218 assert(!tgp->is_active);
219 tgp->shared.context = shared_context;
220 GET_PRIVATE(tgp->shared, cb).is_last_block = 0;
221 tgp->thread_func_ptr = start_routine;
222 }
223
224 // Equivalent to SetThreadFuncAndData() with unchanged
225 // start_routine/shared_context. Ok to call this "unnecessarily".
226 HEADER_INLINE void ReinitThreads(ThreadGroup* tg_ptr) {
227 ThreadGroupMain* tgp = &GET_PRIVATE(*tg_ptr, m);
228 assert(!tgp->is_active);
229 GET_PRIVATE(tgp->shared, cb).is_last_block = 0;
230 }
231
232 HEADER_INLINE uint32_t ThreadsAreActive(ThreadGroup* tg_ptr) {
233 ThreadGroupMain* tgp = &GET_PRIVATE(*tg_ptr, m);
234 return tgp->is_active;
235 }
236
237 // Technically unnecessary to call this, but it does save one sync cycle.
238 //
239 // Note that, if there's only one block of work-shards, this should be called
240 // before the first SpawnThreads() call.
241 HEADER_INLINE void DeclareLastThreadBlock(ThreadGroup* tg_ptr) {
242 ThreadGroupMain* tgp = &GET_PRIVATE(*tg_ptr, m);
243 assert(!tgp->is_unjoined);
244 GET_PRIVATE(tgp->shared, cb).is_last_block = 1;
245 }
246
247 HEADER_INLINE uint32_t IsLastBlock(const ThreadGroup* tg_ptr) {
248 const ThreadGroupMain* tgp = &GET_PRIVATE(*tg_ptr, m);
249 return GET_PRIVATE(tgp->shared, cb).is_last_block;
250 }
251
252 #if defined(__cplusplus) && !defined(_WIN32)
253 class Plink2ThreadStartup {
254 public:
255 pthread_attr_t smallstack_thread_attr;
256 Plink2ThreadStartup() {
257 # ifdef NDEBUG
258 // we'll error out for another reason soon enough if there's insufficient
259 // memory...
260 pthread_attr_init(&smallstack_thread_attr);
261 # else
262 assert(!pthread_attr_init(&smallstack_thread_attr));
263 # endif
264 // if this fails due to kDefaultThreadStack being smaller than the system
265 // page size, no need to error out
266 pthread_attr_setstacksize(&smallstack_thread_attr, kDefaultThreadStack);
267 }
268
269 ~Plink2ThreadStartup() {
270 pthread_attr_destroy(&smallstack_thread_attr);
271 }
272 };
273
274 extern Plink2ThreadStartup g_thread_startup;
275 #endif
276
277 BoolErr SpawnThreads(ThreadGroup* tg_ptr);
278
279 void JoinThreads(ThreadGroup* tg_ptr);
280
281 // Assumes threads are joined.
282 void StopThreads(ThreadGroup* tg_ptr);
283
284 void CleanupThreads(ThreadGroup* tg_ptr);
285
286 #ifdef _WIN32
287 HEADER_INLINE BoolErr THREAD_BLOCK_FINISH(ThreadGroupFuncArg* tgfap) {
288 ThreadGroupControlBlock* cbp = &(GET_PRIVATE(*tgfap->sharedp, cb));
289 if (cbp->is_last_block) {
290 return 1;
291 }
292 const uint32_t start_next_parity = cbp->spawn_ct & 1;
293 if (!__atomic_sub_fetch(&cbp->active_ct, 1, __ATOMIC_ACQ_REL)) {
294 SetEvent(cbp->cur_block_done_event);
295 }
296 WaitForSingleObject(cbp->start_next_events[start_next_parity], INFINITE);
297 return (cbp->is_last_block == 2);
298 }
299 #else
300 BoolErr THREAD_BLOCK_FINISH(ThreadGroupFuncArg* tgfap);
301 #endif
302
303 // Convenience functions for potentially-small-and-frequent jobs where
304 // thread_ct == 0 corresponds to not wanting to launch threads at all; see
305 // MakeDupflagHtable in plink2_cmdline for a typical use case.
306 HEADER_INLINE BoolErr SetThreadCt0(uint32_t thread_ct, ThreadGroup* tg_ptr) {
307 if (!thread_ct) {
308 return 0;
309 }
310 return SetThreadCt(thread_ct, tg_ptr);
311 }
312
313 HEADER_INLINE void JoinThreads0(ThreadGroup* tg_ptr) {
314 if (GET_PRIVATE(*tg_ptr, m).threads) {
315 JoinThreads(tg_ptr);
316 }
317 }
318
319 // This comes in handy a lot in multithreaded error-reporting code when
320 // deterministic behavior is desired.
321 void UpdateU64IfSmaller(uint64_t newval, uint64_t* oldval_ptr);
322
323 void UpdateU32IfSmaller(uint32_t newval, uint32_t* oldval_ptr);
324
325 #ifdef __cplusplus
326 } // namespace plink2
327 #endif
328
329 #endif // __PLINK2_THREAD_H__