sbinet / go-python

naive go bindings to the CPython2 C-API
Other
1.52k stars 138 forks source link

panic when run multi goroutine #108

Closed TXYH1 closed 3 years ago

TXYH1 commented 3 years ago

Hi,my environment is: system: Ubuntu 18.04.5 LTS golang: go1.14 linux/amd64 python version: Python 2.7.17

go code:
func init() {
    err := python.Initialize()
    if err != nil {
        panic(err.Error())
    }
}

func main(){
    m := python.PyImport_AddModule("sys")
    if m == nil {
        panic("fail to import module sys")
    }
    path := m.GetAttrString("path")
    if path == nil {
        panic("fail to get path")
    }

    curPath := python.PyString_FromString("/home/zjf/demopj/python")
    python.PyList_Insert(path, 0, curPath)
    m = python.PyImport_ImportModule("pyDemo")
    if m == nil {
        panic("fail to import module pyDemo")
    }

    func_abc := m.GetAttrString("print_abc")
    if func_abc == nil {
        panic("fail to get func_abc")
    }

    go func() {
        for {
            func_abc.CallFunction()
            time.Sleep(time.Millisecond)
        }
    }()

    go func() {
        for {
            func_abc.CallFunction()
            time.Sleep(time.Millisecond)
        }
    }()
    select {

    }
}

python code:

def print_abc():
    return "abc"
when run the go code, it panic stable, like:

Fatal Python error: GC object already tracked or fatal error: unexpected signal during runtime execution [signal SIGSEGV: segmentation violation code=0x1 addr=0x58 pc=0x7fbec21f9da9]

Can you help me? Thank you very much.

sbinet commented 3 years ago

presumably, that's the CPython's GIL showing its ugly head. you need to serialize calls to the CPython interpreter.

sbinet commented 3 years ago

https://realpython.com/python-gil/

TXYH1 commented 3 years ago

okay, thank you