1 // Copyright 2015 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
11 #include <string.h> // strerror
14 #include "libcgo_unix.h"
16 static pthread_cond_t runtime_init_cond = PTHREAD_COND_INITIALIZER;
17 static pthread_mutex_t runtime_init_mu = PTHREAD_MUTEX_INITIALIZER;
18 static int runtime_init_done;
20 // The context function, used when tracing back C calls into Go.
21 static void (*cgo_context_function)(struct context_arg*);
24 x_cgo_sys_thread_create(void* (*func)(void*), void* arg) {
26 int err = _cgo_try_pthread_create(&p, NULL, func, arg);
28 fprintf(stderr, "pthread_create failed: %s", strerror(err));
34 _cgo_wait_runtime_init_done(void) {
35 void (*pfn)(struct context_arg*);
37 pthread_mutex_lock(&runtime_init_mu);
38 while (runtime_init_done == 0) {
39 pthread_cond_wait(&runtime_init_cond, &runtime_init_mu);
42 // TODO(iant): For the case of a new C thread calling into Go, such
43 // as when using -buildmode=c-archive, we know that Go runtime
44 // initialization is complete but we do not know that all Go init
45 // functions have been run. We should not fetch cgo_context_function
46 // until they have been, because that is where a call to
47 // SetCgoTraceback is likely to occur. We are going to wait for Go
48 // initialization to be complete anyhow, later, by waiting for
49 // main_init_done to be closed in cgocallbackg1. We should wait here
50 // instead. See also issue #15943.
51 pfn = cgo_context_function;
53 pthread_mutex_unlock(&runtime_init_mu);
55 struct context_arg arg;
65 x_cgo_notify_runtime_init_done(void* dummy __attribute__ ((unused))) {
66 pthread_mutex_lock(&runtime_init_mu);
67 runtime_init_done = 1;
68 pthread_cond_broadcast(&runtime_init_cond);
69 pthread_mutex_unlock(&runtime_init_mu);
72 // Sets the context function to call to record the traceback context
73 // when calling a Go function from C code. Called from runtime.SetCgoTraceback.
74 void x_cgo_set_context_function(void (*context)(struct context_arg*)) {
75 pthread_mutex_lock(&runtime_init_mu);
76 cgo_context_function = context;
77 pthread_mutex_unlock(&runtime_init_mu);
80 // Gets the context function.
81 void (*(_cgo_get_context_function(void)))(struct context_arg*) {
82 void (*ret)(struct context_arg*);
84 pthread_mutex_lock(&runtime_init_mu);
85 ret = cgo_context_function;
86 pthread_mutex_unlock(&runtime_init_mu);
90 // _cgo_try_pthread_create retries pthread_create if it fails with
93 _cgo_try_pthread_create(pthread_t* thread, const pthread_attr_t* attr, void* (*pfn)(void*), void* arg) {
98 for (tries = 0; tries < 20; tries++) {
99 err = pthread_create(thread, attr, pfn, arg);
101 pthread_detach(*thread);
108 ts.tv_nsec = (tries + 1) * 1000 * 1000; // Milliseconds.