Debian Codegraph @

include/plink2_thread.cc

raw
1 // This library is part of PLINK 2.0, copyright (C) 2005-2025 Shaun Purcell,
2 // Christopher Chang.
3 //
4 // This library is free software: you can redistribute it and/or modify it
5 // under the terms of the GNU Lesser General Public License as published by the
6 // Free Software Foundation; either version 3 of the License, or (at your
7 // option) any later version.
8 //
9 // This library is distributed in the hope that it will be useful, but WITHOUT
10 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
12 // for more details.
13 //
14 // You should have received a copy of the GNU Lesser General Public License
15 // along with this library. If not, see <http://www.gnu.org/licenses/>.
16
17
18 #include "plink2_thread.h"
19
20 #ifndef _WIN32
21 # ifdef __APPLE__
22 # include <unistd.h> // sysconf()
23 # else
24 # ifndef _GNU_SOURCE
25 # define _GNU_SOURCE
26 # endif
27 # include <sched.h> // sched_getaffinity(), CPU_COUNT()
28 # endif
29 #endif
30
31 #ifdef __cplusplus
32 namespace plink2 {
33 #endif
34
35 static inline ThreadGroupMain* GetTgp(ThreadGroup* tg_ptr) {
36 return &GET_PRIVATE(*tg_ptr, m);
37 }
38
39 static inline ThreadGroupControlBlock* GetCbp(ThreadGroupShared* sharedp) {
40 return &GET_PRIVATE(*sharedp, cb);
41 }
42
43 const char kErrstrThreadCreate[] = "Error: Failed to create thread.\n";
44
45 #ifdef _WIN32
46 void WaitForAllObjects(uint32_t ct, HANDLE* objs) {
47 while (ct > 64) {
48 WaitForMultipleObjects(64, objs, 1, INFINITE);
49 objs = &(objs[64]);
50 ct -= 64;
51 }
52 WaitForMultipleObjects(ct, objs, 1, INFINITE);
53 }
54 #endif
55
56 void PreinitThreads(ThreadGroup* tg_ptr) {
57 ThreadGroupMain* tgp = GetTgp(tg_ptr);
58 GetCbp(&tgp->shared)->thread_ct = 0;
59 GetCbp(&tgp->shared)->is_last_block = 0;
60 tgp->thread_func_ptr = nullptr;
61 tgp->threads = nullptr;
62 tgp->is_unjoined = 0;
63 tgp->is_active = 0;
64 }
65
66 uint32_t NumCpu(int32_t* known_procs_ptr) {
67 #ifdef _WIN32
68 SYSTEM_INFO sysinfo;
69 GetSystemInfo(&sysinfo);
70 const int32_t known_procs = sysinfo.dwNumberOfProcessors;
71 uint32_t max_thread_ct = known_procs;
72 #else
73 # ifdef __APPLE__
74 int32_t known_procs = sysconf(_SC_NPROCESSORS_ONLN);
75 # else
76 int32_t known_procs = -1;
77 cpu_set_t cpu_set;
78 if (sched_getaffinity(0, sizeof(cpu_set), &cpu_set) == 0) {
79 known_procs = CPU_COUNT(&cpu_set);
80 assert(known_procs);
81 }
82 # endif
83 uint32_t max_thread_ct = (known_procs == -1)? 1 : known_procs;
84 #endif
85 if (known_procs_ptr) {
86 *known_procs_ptr = known_procs;
87 }
88 if (max_thread_ct > kMaxThreads) {
89 max_thread_ct = kMaxThreads;
90 }
91 return max_thread_ct;
92 }
93
94 BoolErr SetThreadCt(uint32_t thread_ct, ThreadGroup* tg_ptr) {
95 ThreadGroupMain* tgp = GetTgp(tg_ptr);
96 assert(!tgp->is_active);
97 if (tgp->threads) {
98 free(tgp->threads);
99 tgp->threads = nullptr;
100 }
101 assert(thread_ct && (thread_ct <= kMaxThreads));
102 #ifdef _WIN32
103 unsigned char* memptr = S_CAST(unsigned char*, malloc(thread_ct * (sizeof(ThreadGroupFuncArg) + sizeof(HANDLE))));
104 if (unlikely(!memptr)) {
105 return 1;
106 }
107 tgp->threads = R_CAST(HANDLE*, memptr);
108 memset(tgp->threads, 0, thread_ct * sizeof(HANDLE));
109 memptr = &(memptr[thread_ct * sizeof(HANDLE)]);
110 #else
111 unsigned char* memptr = S_CAST(unsigned char*, malloc(thread_ct * (sizeof(pthread_t) + sizeof(ThreadGroupFuncArg))));
112 if (unlikely(!memptr)) {
113 return 1;
114 }
115 tgp->threads = R_CAST(pthread_t*, memptr);
116 // !is_active currently guarantees that the sync events/mutex/condvars are
117 // not initialized. Could change this later.
118 tgp->sync_init_state = 0;
119 memptr = &(memptr[thread_ct * sizeof(pthread_t)]);
120 #endif
121 ThreadGroupControlBlock* cbp = GetCbp(&tgp->shared);
122 cbp->active_ct = 0;
123 tgp->thread_args = R_CAST(ThreadGroupFuncArg*, memptr);
124
125 cbp->thread_ct = thread_ct;
126 return 0;
127 }
128
129 // Note that thread_ct is permitted to be less than tgp->shared.cb.thread_ct,
130 // to support the SpawnThreads() error cases.
131 void JoinThreadsInternal(uint32_t thread_ct, ThreadGroupMain* tgp) {
132 assert(tgp->is_active);
133 ThreadGroupControlBlock* cbp = GetCbp(&tgp->shared);
134 #ifdef _WIN32
135 if (!cbp->is_last_block) {
136 WaitForSingleObject(cbp->cur_block_done_event, INFINITE);
137 } else {
138 WaitForAllObjects(thread_ct, tgp->threads);
139 for (uint32_t tidx = 0; tidx != thread_ct; ++tidx) {
140 CloseHandle(tgp->threads[tidx]);
141 }
142 CloseHandle(cbp->start_next_events[0]);
143 CloseHandle(cbp->start_next_events[1]);
144 CloseHandle(cbp->cur_block_done_event);
145 memset(tgp->threads, 0, thread_ct * sizeof(HANDLE));
146 tgp->is_active = 0;
147 }
148 #else
149 if (!cbp->is_last_block) {
150 pthread_mutex_lock(&cbp->sync_mutex);
151 while (cbp->active_ct) {
152 pthread_cond_wait(&cbp->cur_block_done_condvar, &cbp->sync_mutex);
153 }
154 // keep mutex until next block loaded
155 } else {
156 for (uint32_t tidx = 0; tidx != thread_ct; ++tidx) {
157 pthread_join(tgp->threads[tidx], nullptr);
158 }
159 pthread_mutex_destroy(&cbp->sync_mutex);
160 pthread_cond_destroy(&cbp->cur_block_done_condvar);
161 pthread_cond_destroy(&cbp->start_next_condvar);
162 tgp->is_active = 0;
163 tgp->sync_init_state = 0;
164 }
165 #endif
166 tgp->is_unjoined = 0;
167 }
168
169 #if defined(__cplusplus) && !defined(_WIN32)
170 Plink2ThreadStartup g_thread_startup;
171 #endif
172
173 BoolErr SpawnThreads(ThreadGroup* tg_ptr) {
174 ThreadGroupMain* tgp = GetTgp(tg_ptr);
175 ThreadGroupControlBlock* cbp = GetCbp(&tgp->shared);
176 const uint32_t thread_ct = cbp->thread_ct;
177 const uint32_t was_active = tgp->is_active;
178 const uint32_t is_last_block = cbp->is_last_block;
179 pthread_t* threads = tgp->threads;
180 assert(threads != nullptr);
181 #ifdef _WIN32
182 if (!was_active) {
183 cbp->spawn_ct = 0;
184 // manual-reset broadcast event
185 HANDLE cur_event = CreateEvent(nullptr, TRUE, FALSE, nullptr);
186 if (unlikely(!cur_event)) {
187 return 1;
188 }
189 cbp->start_next_events[0] = cur_event;
190 cur_event = CreateEvent(nullptr, TRUE, FALSE, nullptr);
191 if (unlikely(!cur_event)) {
192 CloseHandle(cbp->start_next_events[0]);
193 return 1;
194 }
195 cbp->start_next_events[1] = cur_event;
196 cur_event = CreateEvent(nullptr, FALSE, FALSE, nullptr);
197 if (unlikely(!cur_event)) {
198 CloseHandle(cbp->start_next_events[0]);
199 CloseHandle(cbp->start_next_events[1]);
200 return 1;
201 }
202 cbp->cur_block_done_event = cur_event;
203 cbp->active_ct = thread_ct;
204 for (uint32_t tidx = 0; tidx != thread_ct; ++tidx) {
205 ThreadGroupFuncArg* arg_slot = &(tgp->thread_args[tidx]);
206 arg_slot->sharedp = &(tgp->shared);
207 arg_slot->tidx = tidx;
208 threads[tidx] = R_CAST(HANDLE, _beginthreadex(nullptr, kDefaultThreadStack, tgp->thread_func_ptr, arg_slot, 0, nullptr));
209 if (unlikely(!threads[tidx])) {
210 if (tidx) {
211 if (!is_last_block) {
212 // not sure the old TerminateThread() code ever worked properly in
213 // the first place...
214 // anyway, new contract makes clean error-shutdown easy
215 if (!__atomic_sub_fetch(&cbp->active_ct, thread_ct - tidx, __ATOMIC_ACQ_REL)) {
216 SetEvent(cbp->cur_block_done_event);
217 }
218 JoinThreadsInternal(tidx, tgp);
219 cbp->is_last_block = 2;
220 const uint32_t start_next_parity = cbp->spawn_ct & 1;
221 // no need to reset start_prev_parity
222 cbp->spawn_ct += 1;
223 SetEvent(cbp->start_next_events[start_next_parity]);
224 }
225 JoinThreadsInternal(tidx, tgp);
226 }
227 return 1;
228 }
229 }
230 tgp->is_active = 1;
231 } else {
232 cbp->spawn_ct += 1;
233 cbp->active_ct = thread_ct;
234 const uint32_t start_prev_parity = cbp->spawn_ct & 1;
235 ResetEvent(cbp->start_next_events[start_prev_parity]);
236 SetEvent(cbp->start_next_events[start_prev_parity ^ 1]);
237 }
238 #else
239 if (!is_last_block) {
240 cbp->active_ct = thread_ct;
241 }
242 if (!was_active) {
243 cbp->spawn_ct = 0;
244 assert(!tgp->sync_init_state);
245 if (unlikely(pthread_mutex_init(&cbp->sync_mutex, nullptr))) {
246 return 1;
247 }
248 if (unlikely(pthread_cond_init(&cbp->cur_block_done_condvar, nullptr))) {
249 tgp->sync_init_state = 1;
250 return 1;
251 }
252 if (unlikely(pthread_cond_init(&cbp->start_next_condvar, nullptr))) {
253 tgp->sync_init_state = 2;
254 return 1;
255 }
256 tgp->sync_init_state = 3;
257 # ifndef __cplusplus
258 pthread_attr_t smallstack_thread_attr;
259 if (unlikely(pthread_attr_init(&smallstack_thread_attr))) {
260 return 1;
261 }
262 pthread_attr_setstacksize(&smallstack_thread_attr, kDefaultThreadStack);
263 # endif
264 for (uint32_t tidx = 0; tidx != thread_ct; ++tidx) {
265 ThreadGroupFuncArg* arg_slot = &(tgp->thread_args[tidx]);
266 arg_slot->sharedp = &(tgp->shared);
267 arg_slot->tidx = tidx;
268 const int32_t pthread_create_result =
269 pthread_create(&(threads[tidx]),
270 # ifdef __cplusplus
271 &g_thread_startup.smallstack_thread_attr,
272 # else
273 &smallstack_thread_attr,
274 # endif
275 tgp->thread_func_ptr, arg_slot);
276 if (unlikely(pthread_create_result)) {
277 if (tidx) {
278 if (!is_last_block) {
279 JoinThreadsInternal(tidx, tgp);
280 const uint32_t unstarted_thread_ct = thread_ct - tidx;
281 cbp->active_ct -= unstarted_thread_ct;
282 while (cbp->active_ct) {
283 pthread_cond_wait(&cbp->cur_block_done_condvar, &cbp->sync_mutex);
284 }
285 cbp->is_last_block = 2;
286 cbp->spawn_ct += 1;
287 pthread_cond_broadcast(&cbp->start_next_condvar);
288 pthread_mutex_unlock(&cbp->sync_mutex);
289 }
290 JoinThreadsInternal(tidx, tgp);
291 } else {
292 cbp->active_ct = 0;
293 }
294 # ifndef __cplusplus
295 pthread_attr_destroy(&smallstack_thread_attr);
296 # endif
297 return 1;
298 }
299 }
300 # ifndef __cplusplus
301 pthread_attr_destroy(&smallstack_thread_attr);
302 # endif
303 tgp->is_active = 1;
304 } else {
305 cbp->spawn_ct += 1;
306 // still holding mutex
307 pthread_cond_broadcast(&cbp->start_next_condvar);
308 pthread_mutex_unlock(&cbp->sync_mutex);
309 }
310 #endif
311 tgp->is_unjoined = 1;
312 return 0;
313 }
314
315 void JoinThreads(ThreadGroup* tg_ptr) {
316 ThreadGroupMain* tgp = GetTgp(tg_ptr);
317 JoinThreadsInternal(GetCbp(&tgp->shared)->thread_ct, tgp);
318 }
319
320 void StopThreads(ThreadGroup* tg_ptr) {
321 ThreadGroupMain* tgp = GetTgp(tg_ptr);
322 ThreadGroupControlBlock* cbp = GetCbp(&tgp->shared);
323 cbp->is_last_block = 2;
324 SpawnThreads(tg_ptr);
325 JoinThreadsInternal(cbp->thread_ct, tgp);
326 }
327
328 void CleanupThreads(ThreadGroup* tg_ptr) {
329 ThreadGroupMain* tgp = GetTgp(tg_ptr);
330 ThreadGroupControlBlock* cbp = GetCbp(&tgp->shared);
331 if (tgp->threads) {
332 const uint32_t thread_ct = cbp->thread_ct;
333 if (tgp->is_active) {
334 if (tgp->is_unjoined) {
335 JoinThreadsInternal(thread_ct, tgp);
336 }
337 if (!cbp->is_last_block) {
338 StopThreads(tg_ptr);
339 }
340 #ifndef _WIN32
341 } else {
342 do {
343 const uint32_t sync_init_state = tgp->sync_init_state;
344 if (!sync_init_state) {
345 break;
346 }
347 pthread_mutex_destroy(&cbp->sync_mutex);
348 if (sync_init_state == 1) {
349 break;
350 }
351 pthread_cond_destroy(&cbp->cur_block_done_condvar);
352 if (sync_init_state == 2) {
353 break;
354 }
355 pthread_cond_destroy(&cbp->start_next_condvar);
356 } while (0);
357 tgp->sync_init_state = 0;
358 #endif
359 }
360 #ifndef _WIN32
361 assert(!cbp->active_ct);
362 #endif
363 cbp->thread_ct = 0;
364 free(tgp->threads);
365 tgp->threads = nullptr;
366 }
367 cbp->is_last_block = 0;
368 tgp->thread_func_ptr = nullptr;
369 }
370
371 #ifndef _WIN32
372 BoolErr THREAD_BLOCK_FINISH(ThreadGroupFuncArg* tgfap) {
373 ThreadGroupControlBlock* cbp = GetCbp(tgfap->sharedp);
374 if (cbp->is_last_block) {
375 return 1;
376 }
377 const uintptr_t initial_spawn_ct = cbp->spawn_ct;
378 pthread_mutex_lock(&cbp->sync_mutex);
379 if (!(--cbp->active_ct)) {
380 pthread_cond_signal(&cbp->cur_block_done_condvar);
381 }
382 while (cbp->spawn_ct == initial_spawn_ct) {
383 // spurious wakeup guard
384 pthread_cond_wait(&cbp->start_next_condvar, &cbp->sync_mutex);
385 }
386 pthread_mutex_unlock(&cbp->sync_mutex);
387 return (cbp->is_last_block == 2);
388 }
389 #endif
390
391 void UpdateU64IfSmaller(uint64_t newval, uint64_t* oldval_ptr) {
392 uint64_t oldval = *oldval_ptr;
393 while (oldval > newval) {
394 if (ATOMIC_COMPARE_EXCHANGE_N_U64(oldval_ptr, &oldval, newval, 1, __ATOMIC_RELAXED, __ATOMIC_RELAXED)) {
395 break;
396 }
397 }
398 }
399
400 void UpdateU32IfSmaller(uint32_t newval, uint32_t* oldval_ptr) {
401 uint32_t oldval = *oldval_ptr;
402 while (oldval > newval) {
403 if (ATOMIC_COMPARE_EXCHANGE_N_U32(oldval_ptr, &oldval, newval, 1, __ATOMIC_RELAXED, __ATOMIC_RELAXED)) {
404 break;
405 }
406 }
407 }
408
409 #ifdef __cplusplus
410 } // namespace plink2
411 #endif