summaryrefslogtreecommitdiff
path: root/libgo/go/runtime/testdata/testprogcgo/callback.go
blob: 10e248a15908ef2d49f6a04a9b13d5cc8b3c63a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Copyright 2015 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build !plan9,!windows

package main

/*
#include <pthread.h>

void go_callback();

static void *thr(void *arg) {
    go_callback();
    return 0;
}

static void foo() {
    pthread_t th;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setstacksize(&attr, 256 << 10);
    pthread_create(&th, &attr, thr, 0);
    pthread_join(th, 0);
}
*/
import "C"

import (
	"fmt"
	"runtime"
)

func init() {
	register("CgoCallbackGC", CgoCallbackGC)
}

//export go_callback
func go_callback() {
	runtime.GC()
	grow()
	runtime.GC()
}

var cnt int

func grow() {
	x := 10000
	sum := 0
	if grow1(&x, &sum) == 0 {
		panic("bad")
	}
}

func grow1(x, sum *int) int {
	if *x == 0 {
		return *sum + 1
	}
	*x--
	sum1 := *sum + *x
	return grow1(x, &sum1)
}

func CgoCallbackGC() {
	const P = 100
	done := make(chan bool)
	// allocate a bunch of stack frames and spray them with pointers
	for i := 0; i < P; i++ {
		go func() {
			grow()
			done <- true
		}()
	}
	for i := 0; i < P; i++ {
		<-done
	}
	// now give these stack frames to cgo callbacks
	for i := 0; i < P; i++ {
		go func() {
			C.foo()
			done <- true
		}()
	}
	for i := 0; i < P; i++ {
		<-done
	}
	fmt.Printf("OK\n")
}