go-python/cpy3

how can i call python3 function in groutine

xxz199539 opened this issue · 2 comments

image
I get this error when i call py func in groutine

Try the following:

  1. Lock your goroutine to the thread: runtime.LockOSThread(); defer runtime.UnlockOSThread() - to avoid it jumping between threads while python code is called
  2. Make sure you acquire GIL in the coroutine's thread: gilstate := py.PyGILState_Ensure(); defer py.PyGILState_Release(gilstate) - so that GIL is acquired while you call Python code
  3. Now you should be safe to call Python code.

I cannot tell more without seeing your code. A minimal reproducing example would be ideal.

Quoting from a previous issue:

This project is just a relatively thin wrapper around Python's C API. So basically all the limitations of the Python C API apply. One limitation is that Python has a global interpreter lock (GIL). You can't do multiple things in a Python interpreter at the same time (unless you use Python's concurrency features in the Python code that you're executing).

The easiest way to make embedded Python to work with goroutines is to make sure that only one goroutine is actually "doing" Python at a time and all the other ones have to wait. Here's an excellent blog post and related conference talk that cover this and a few other options.