Debian Codegraph @

src/thread.c

raw
1 /*
2 * thread.c - Scheme thread API
3 *
4 * Copyright (c) 2000-2024 Shiro Kawai <[email protected]>
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 *
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 *
17 * 3. Neither the name of the authors nor the names of its contributors
18 * may be used to endorse or promote products derived from this
19 * software without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
27 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34 #define LIBGAUCHE_BODY
35 #include "gauche.h"
36 #include "gauche/priv/configP.h"
37 #include "gauche/vm.h"
38 #include "gauche/exception.h"
39 #include "gauche/priv/vmP.h"
40
41 #ifdef HAVE_UNISTD_H
42 #include <unistd.h>
43 #endif
44 #ifdef HAVE_SCHED_H
45 #include <sched.h>
46 #endif
47
48 /*==============================================================
49 * Thread interface
50 */
51
52 /* Creation. In the "NEW" state, a VM is allocated but actual thread
53 is not created. */
54 ScmObj Scm_MakeThread(ScmProcedure *thunk, ScmObj name)
55 {
56 ScmVM *current = Scm_VM();
57
58 if (SCM_PROCEDURE_REQUIRED(thunk) != 0) {
59 Scm_Error("thunk required, but got %S", thunk);
60 }
61 ScmVM *vm = Scm_NewVM(current, name);
62 vm->thunk = thunk;
63 return SCM_OBJ(vm);
64 }
65
66 /* Common routine for proper shutdown of a thread. Usually this is called
67 by the thread owning VM, via pthread_cleanup mechanism. However, in the
68 emergency shutdown, the canceller thread may call this
69 (see Scm_ThreadTerminate below).
70 Caller must hold vm->vmlock */
71 static void thread_cleanup_inner(ScmVM *vm)
72 {
73 /* Change this VM state to TERMINATED, and signals the change
74 to the waiting threads. */
75 vm->state = SCM_VM_TERMINATED;
76 if (vm->canceller) {
77 /* This thread is cancelled. */
78 ScmObj e = Scm_MakeThreadException(
79 SCM_CLASS_TERMINATED_THREAD_EXCEPTION, vm);
80 SCM_THREAD_EXCEPTION(e)->data = SCM_OBJ(vm->canceller);
81 vm->resultException = e;
82 }
83 SCM_INTERNAL_COND_BROADCAST(vm->cond);
84 }
85
86 /* Called by pthread_cleanup mechanism. After this, Scm_VM() won't return
87 a valid VM pointer. */
88 static void thread_cleanup(void *data)
89 {
90 ScmVM *vm = SCM_VM(data);
91 SCM_INTERNAL_MUTEX_LOCK(vm->vmlock);
92 thread_cleanup_inner(vm);
93 SCM_INTERNAL_MUTEX_UNLOCK(vm->vmlock);
94 Scm_DetachVM(vm);
95 }
96
97 static SCM_INTERNAL_THREAD_PROC_RETTYPE thread_entry(void *data)
98 {
99 ScmVM *vm = SCM_VM(data);
100
101 if (!Scm_AttachVM(vm)) {
102 vm->resultException =
103 Scm_MakeError(SCM_MAKE_STR("attaching VM to thread failed"));
104 thread_cleanup(vm);
105 } else {
106 SCM_INTERNAL_THREAD_CLEANUP_PUSH(thread_cleanup, vm);
107 SCM_UNWIND_PROTECT {
108 vm->result = Scm_ApplyRec(SCM_OBJ(vm->thunk), SCM_NIL);
109 } SCM_WHEN_ERROR {
110 switch (vm->escapeReason) {
111 case SCM_VM_ESCAPE_CONT:
112 /*TODO: better message*/
113 vm->resultException =
114 Scm_MakeError(SCM_MAKE_STR("stale continuation thrown"));
115 break;
116 case SCM_VM_ESCAPE_ERROR: {
117 /* Error handling is delegated to the thread that calls
118 thread-join!. */
119 ScmObj exc =
120 Scm_MakeThreadException(SCM_CLASS_UNCAUGHT_EXCEPTION, vm);
121 SCM_THREAD_EXCEPTION(exc)->data = SCM_OBJ(vm->escapeData[1]);
122 vm->resultException = exc;
123 break;
124 }
125 default:
126 Scm_Panic("unknown escape");
127 }
128 } SCM_END_PROTECT;
129 SCM_INTERNAL_THREAD_CLEANUP_POP();
130 }
131 return SCM_INTERNAL_THREAD_PROC_RETVAL;
132 }
133
134 #if defined(GAUCHE_USE_PTHREADS)
135 /* The default signal mask on the thread creation */
136 static struct threadRec {
137 sigset_t defaultSigmask;
138 } threadrec;
139 #endif /* GAUCHE_USE_PTHREADS */
140
141 /* Start a thread. If the VM is in "NEW" state, create a new thread and
142 make it run.
143
144 With pthread, the real thread is started as "detached" mode; i.e. once
145 the thread exits, the resources allocated for the thread by the system
146 is collected, including the result of the thread. During this
147 deconstruction phase, the handler thread_cleanup() runs and saves the
148 thread result to the ScmVM structure. If nobody cares about the
149 result of the thread, ScmVM structure will eventually be GCed.
150 This is to prevent exited thread's system resources from being
151 uncollected.
152 */
153 ScmObj Scm_ThreadStart(ScmVM *vm, u_long flags)
154 {
155 int err_state = FALSE, err_create = FALSE;
156
157 (void)SCM_INTERNAL_MUTEX_LOCK(vm->vmlock);
158 if (vm->state != SCM_VM_NEW) {
159 err_state = TRUE;
160 } else {
161 SCM_ASSERT(vm->thunk);
162 vm->state = SCM_VM_RUNNABLE;
163 #if defined(GAUCHE_USE_PTHREADS)
164 {
165 pthread_attr_t thattr;
166 sigset_t omask;
167 pthread_attr_init(&thattr);
168 pthread_attr_setdetachstate(&thattr, PTHREAD_CREATE_DETACHED);
169 pthread_sigmask(SIG_SETMASK, &threadrec.defaultSigmask, &omask);
170 if (pthread_create(&vm->thread, &thattr, thread_entry, vm) != 0) {
171 vm->state = SCM_VM_NEW;
172 err_create = TRUE;
173 }
174 pthread_sigmask(SIG_SETMASK, &omask, NULL);
175 pthread_attr_destroy(&thattr);
176 }
177 #elif defined(GAUCHE_USE_WTHREADS)
178 {
179 HANDLE h = GC_CreateThread(NULL, /* security */
180 0, /* default stack size */
181 thread_entry, /* start proc */
182 vm, /* parameter */
183 0, /* flags */
184 NULL); /* thread id receiver */
185 if (h != NULL) {
186 vm->thread = h;
187 } else {
188 vm->state = SCM_VM_NEW;
189 err_create = TRUE;
190 }
191 }
192 #else /* no threads */
193 Scm_Error("Thread is not available.");
194 #endif
195 }
196 (void)SCM_INTERNAL_MUTEX_UNLOCK(vm->vmlock);
197 if (err_state) {
198 if (flags & SCM_THREAD_START_TRYSTART) {
199 return SCM_FALSE;
200 }
201 Scm_Error("attempt to start an already-started thread: %S", vm);
202 }
203 if (err_create) Scm_Error("couldn't start a new thread: %S", vm);
204 return SCM_OBJ(vm);
205 }
206
207 /* Thread join */
208 ScmObj Scm_ThreadJoin(ScmVM *target, ScmObj timeout, volatile ScmObj timeoutval)
209 {
210 ScmTimeSpec ts;
211 volatile ScmObj result = SCM_FALSE, resultx = SCM_FALSE;
212 volatile int intr = FALSE, tout = FALSE;
213
214 ScmTimeSpec *pts = Scm_GetTimeSpec(timeout, &ts);
215 SCM_INTERNAL_MUTEX_SAFE_LOCK_BEGIN(target->vmlock);
216 while (target->state != SCM_VM_TERMINATED) {
217 if (pts) {
218 int tr = SCM_INTERNAL_COND_TIMEDWAIT(target->cond, target->vmlock, pts);
219 if (tr == SCM_INTERNAL_COND_TIMEDOUT) { tout = TRUE; break; }
220 else if (tr == SCM_INTERNAL_COND_INTR) { intr = TRUE; break; }
221 } else {
222 SCM_INTERNAL_COND_WAIT(target->cond, target->vmlock);
223 }
224 }
225 if (!tout) {
226 result = target->result; resultx = target->resultException;
227 target->resultException = SCM_FALSE; /* clear it */
228 }
229 SCM_INTERNAL_MUTEX_SAFE_LOCK_END();
230 if (intr) Scm_SigCheck(Scm_VM());
231 if (tout) {
232 if (SCM_UNBOUNDP(timeoutval)) {
233 ScmObj e = Scm_MakeThreadException(SCM_CLASS_JOIN_TIMEOUT_EXCEPTION, target);
234 result = Scm_Raise(e, 0);
235 } else {
236 result = timeoutval;
237 }
238 } else if (SCM_CONDITIONP(resultx)) {
239 result = Scm_Raise(resultx, 0);
240 }
241 return result;
242 }
243
244 /* Attempt to stop other thread. See process_queued_requests() in vm.c
245 for the target VM operation.
246
247 VM Stop protocol:
248
249 target inspector
250 ------------------------------------------------------------------------
251 * LOCK(target->vmlock)
252 * Check if target is already inspected
253 * Set target's STOP flag
254 * Wait on target->cond
255 until target->state becomes STOPPED
256 * If STOP flag is up,
257 set self->state to STOPPED
258 and signal self->cond
259 then wait on self->cond until
260 target->state changes from STOPPED
261 * Inspect target VM state
262 * Set taget->state to RUNNABLE,
263 then signal state->cond
264 * Resume execution
265 -------------------------------------------------------------------------
266 */
267
268 ScmObj Scm_ThreadStop(ScmVM *target, ScmObj timeout, ScmObj timeoutval)
269 {
270 ScmTimeSpec ts;
271 ScmVM *vm = Scm_VM();
272 ScmVM *taker = NULL;
273 int timedout;
274 int invalid_state = FALSE;
275 ScmTimeSpec *pts = Scm_GetTimeSpec(timeout, &ts);
276
277 retry:
278 timedout = FALSE;
279 SCM_INTERNAL_MUTEX_LOCK(target->vmlock);
280 if (target->state != SCM_VM_RUNNABLE
281 && target->state != SCM_VM_STOPPED) {
282 invalid_state = TRUE;
283 } else if (target->inspector != NULL
284 && target->inspector != vm
285 && target->inspector->state != SCM_VM_TERMINATED) {
286 taker = target->inspector;
287 } else {
288 /* NB: if target->inspector == vm, it means we have requested to
289 stop the thread before, and haven't called ThreadCont yet.
290 In that case we don't need to set stopRequest again; either target
291 thread already cleared it and stopped/going to stop, or
292 the target thread hasn't seen the flag and it's still ON. */
293 if (target->inspector != vm) {
294 target->inspector = vm;
295 target->stopRequest = SCM_VM_REQUEST_SUSPEND;
296 target->attentionRequest = TRUE;
297 }
298 while (target->state != SCM_VM_STOPPED && !timedout) {
299 if (pts) {
300 timedout = SCM_INTERNAL_COND_TIMEDWAIT(target->cond,
301 target->vmlock,
302 pts);
303 } else {
304 SCM_INTERNAL_COND_WAIT(target->cond, target->vmlock);
305 }
306 }
307 }
308 SCM_INTERNAL_MUTEX_UNLOCK(target->vmlock);
309
310 if (invalid_state) {
311 Scm_Error("cannot stop a thread %S since it is in neither runnable nor stopped state",
312 target);
313 }
314 if (taker != NULL) {
315 Scm_Error("target %S is already under inspection by %S", target, taker);
316 }
317
318 if (timedout == SCM_INTERNAL_COND_INTR) { Scm_SigCheck(vm); goto retry; }
319 if (timedout == SCM_INTERNAL_COND_TIMEDOUT) return timeoutval;
320 return SCM_OBJ(target);
321 }
322
323
324 /* Release inspected thread */
325 ScmObj Scm_ThreadCont(ScmVM *target)
326 {
327 int not_stopped = FALSE;
328 ScmVM *stopped_by_other = NULL;
329
330 SCM_INTERNAL_MUTEX_LOCK(target->vmlock);
331 if (target->inspector == NULL) {
332 not_stopped = TRUE;
333 } else if (target->inspector != Scm_VM()
334 && target->inspector->state != SCM_VM_TERMINATED) {
335 stopped_by_other = target->inspector;
336 } else {
337 target->inspector = NULL;
338 target->state = SCM_VM_RUNNABLE;
339 target->stopRequest = 0;
340 SCM_INTERNAL_COND_BROADCAST(target->cond);
341 }
342 SCM_INTERNAL_MUTEX_UNLOCK(target->vmlock);
343 if (not_stopped) Scm_Error("target %S is not stopped", target);
344 if (stopped_by_other) Scm_Error("target %S is stopped by other thread %S",
345 target, stopped_by_other);
346 return SCM_OBJ(target);
347 }
348
349 /* Thread sleep */
350 ScmObj Scm_ThreadSleep(ScmObj timeout)
351 {
352 ScmTimeSpec ts;
353 ScmInternalCond dummyc;
354 ScmInternalMutex dummym;
355 int intr = FALSE;
356
357 SCM_INTERNAL_COND_INIT(dummyc);
358 SCM_INTERNAL_MUTEX_INIT(dummym);
359 ScmTimeSpec *pts = Scm_GetTimeSpec(timeout, &ts);
360 if (pts == NULL) Scm_Error("thread-sleep! can't take #f as a timeout value");
361 SCM_INTERNAL_MUTEX_LOCK(dummym);
362 if (SCM_INTERNAL_COND_TIMEDWAIT(dummyc, dummym, pts) == SCM_INTERNAL_COND_INTR) {
363 intr = TRUE;
364 }
365 SCM_INTERNAL_MUTEX_UNLOCK(dummym);
366 SCM_INTERNAL_MUTEX_DESTROY(dummym);
367 SCM_INTERNAL_COND_DESTROY(dummyc);
368 if (intr) Scm_SigCheck(Scm_VM());
369 return SCM_UNDEFINED;
370 }
371
372 /* Thread termination
373
374 We try to terminate the thread gracefully as possible.
375 First, we use vm->stopRequest mechanism. If the target thread is
376 in VM loop, it responds to the flag and terminates itself.
377
378 If that fails, we send a signal to the thread. If the thread is blocked
379 by a system call, this most likely unblocks the thread and termnates it.
380 (We use a dedicated signal.
381
382 There are cases when signals can fail. On POSIX platform, if the thread
383 is waiting on pthread_cond_wait, it is not guaranteed to be interrupted
384 with a signal. On Windows platform, system calls can't be interrupted
385 so we don't have this option. (We may, in future, use CancelSynchronousIo
386 to interrupt at least synchronous I/O calls).
387
388 If the above steps all fails and SCM_THREAD_TERIMINATE_FORCIBLE is passed
389 in FLAGS, we resort to use pthread_cancel or TerminateThread. This is not
390 safe---the thread may leave memory in inconsistent state.
391
392 In any way, the target thread is marked as SCM_VM_TERMINATED. If we
393 avoid the forcible termiantion, the thread remains in the system, but
394 as soon as it unblocks and resumes execution of Gauche code, it will
395 see the terminate request and terminate itself.
396 */
397
398 /* Caller must hold target->vmlock. return TRUE if the target terminates
399 gracefully. */
400 static int wait_for_termination(ScmVM *target)
401 {
402 ScmTimeSpec ts;
403 int r;
404 ScmObj t = Scm_MakeFlonum(0.001); /* 1ms. somewhat arbitrary */
405 Scm_GetTimeSpec(t, &ts);
406 do {
407 r = SCM_INTERNAL_COND_TIMEDWAIT(target->cond, target->vmlock, &ts);
408 } while (r != SCM_INTERNAL_COND_TIMEDOUT
409 && target->state != SCM_VM_TERMINATED);
410 return (r == 0);
411 }
412
413 ScmObj Scm_ThreadTerminate(ScmVM *target, u_long flags)
414 {
415 ScmVM *vm = Scm_VM();
416 if (target == vm) {
417 /* self termination */
418 (void)SCM_INTERNAL_MUTEX_LOCK(target->vmlock);
419 if (target->canceller == NULL) {
420 target->canceller = vm;
421 }
422 (void)SCM_INTERNAL_MUTEX_UNLOCK(target->vmlock);
423 /* Need to unlock before calling pthread_exit(), or the cleanup
424 routine can't obtain the lock */
425 SCM_INTERNAL_THREAD_EXIT();
426 /*NOTREACHED*/
427 }
428
429 (void)SCM_INTERNAL_MUTEX_LOCK(target->vmlock);
430 if (target->state != SCM_VM_TERMINATED) {
431 /* This ensures only the first call of thread-terminate! on a
432 thread is in effect. */
433 if (target->canceller == NULL) {
434 target->canceller = vm;
435
436 if (target->state == SCM_VM_NEW) {
437 /* The thread is being killed before started. We don't have
438 the actual thread, so just clean up. */
439 thread_cleanup_inner(target);
440 } else {
441 do {
442 /* First try */
443 target->stopRequest = SCM_VM_REQUEST_TERMINATE;
444 target->attentionRequest = TRUE;
445 if (flags & SCM_THREAD_TERMINATE_SCHEDULE) break;
446 if (wait_for_termination(target)) break;
447
448 /* Second try */
449 SCM_ASSERT(target->thread);
450 #if defined(GAUCHE_USE_PTHREADS)
451 # if defined(GAUCHE_PTHREAD_SIGNAL)
452 pthread_kill(target->thread, GAUCHE_PTHREAD_SIGNAL);
453 # endif /*defined(GAUCHE_PTHREAD_SIGNAL)*/
454 #elif defined(GAUCHE_USE_WTHREADS)
455 /* TODO: implement signal mechanism using an event */
456 #endif /* defined(GAUCHE_USE_WTHREADS) */
457 if (wait_for_termination(target)) break;
458
459 thread_cleanup_inner(target);
460
461 /* If forcible termination is requested, we resort to
462 the extreme measure. */
463 if (flags & SCM_THREAD_TERMINATE_FORCIBLE) {
464 #if defined(GAUCHE_USE_PTHREADS)
465 # if defined(HAVE_PTHREAD_CANCEL)
466 /* pthread_cancel() may be redirected to
467 GC_pthread_cancel(), but that only happens
468 if the system has pthread_cancel anyway.
469 */
470 pthread_cancel(target->thread);
471 # else
472 /* The system lacks pthread_cancel(), e.g. on Android.
473 https://github.com/shirok/Gauche/issues/790
474 We have no choice but do nothing. */
475 ;
476 # endif
477 #elif defined(GAUCHE_USE_WTHREADS)
478 TerminateThread(target->thread, 0);
479 #endif
480 }
481 } while (0);
482 }
483 }
484 }
485 /* target either is terminated or hasn't been run */
486 (void)SCM_INTERNAL_MUTEX_UNLOCK(target->vmlock);
487 return SCM_UNDEFINED;
488 }
489
490 /*
491 * Initialization.
492 */
493 void Scm__InitThreads()
494 {
495 #ifdef GAUCHE_USE_PTHREADS
496 sigfillset(&threadrec.defaultSigmask);
497 # if defined(GAUCHE_PTHREAD_SIGNAL)
498 sigdelset(&threadrec.defaultSigmask, GAUCHE_PTHREAD_SIGNAL);
499 # endif /*defined(GAUCHE_PTHRAD_SIGNAL)*/
500 #endif /*GAUCHE_USE_PTHREADS*/
501 }