Debian Codegraph @

libgo/go/runtime/testdata/testprogcgo/callback.go

raw
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.
4
5 //go:build !plan9 && !windows
6 // +build !plan9,!windows
7
8 package main
9
10 /*
11 #cgo CFLAGS: -pthread
12 #cgo LDFLAGS: -pthread
13
14 #include <pthread.h>
15
16 void go_callback();
17
18 static void *thr(void *arg) {
19 go_callback();
20 return 0;
21 }
22
23 static void foo() {
24 pthread_t th;
25 pthread_attr_t attr;
26 pthread_attr_init(&attr);
27 // For gccgo use a stack size large enough for all the callbacks,
28 // in case we are on a platform that does not support -fsplit-stack.
29 pthread_attr_setstacksize(&attr, 512 * 10000);
30 pthread_create(&th, &attr, thr, 0);
31 pthread_join(th, 0);
32 }
33 */
34 import "C"
35
36 import (
37 "fmt"
38 "os"
39 "runtime"
40 )
41
42 func init() {
43 register("CgoCallbackGC", CgoCallbackGC)
44 }
45
46 //export go_callback
47 func go_callback() {
48 runtime.GC()
49 grow()
50 runtime.GC()
51 }
52
53 var cnt int
54
55 func grow() {
56 x := 10000
57 sum := 0
58 if grow1(&x, &sum) == 0 {
59 panic("bad")
60 }
61 }
62
63 func grow1(x, sum *int) int {
64 if *x == 0 {
65 return *sum + 1
66 }
67 *x--
68 sum1 := *sum + *x
69 return grow1(x, &sum1)
70 }
71
72 func CgoCallbackGC() {
73 P := 100
74 if os.Getenv("RUNTIME_TEST_SHORT") != "" {
75 P = 10
76 }
77 done := make(chan bool)
78 // allocate a bunch of stack frames and spray them with pointers
79 for i := 0; i < P; i++ {
80 go func() {
81 grow()
82 done <- true
83 }()
84 }
85 for i := 0; i < P; i++ {
86 <-done
87 }
88 // now give these stack frames to cgo callbacks
89 for i := 0; i < P; i++ {
90 go func() {
91 C.foo()
92 done <- true
93 }()
94 }
95 for i := 0; i < P; i++ {
96 <-done
97 }
98 fmt.Printf("OK\n")
99 }