# Using pycall from threads

**URL:** <https://discourse.julialang.org/t/using-pycall-from-threads/32742>\
**Category:** New to Julia\
**Tags:** pycall, multithreading\
**Created:** [December 27, 2019, 4:04pm UTC](https://discourse.julialang.org/t/using-pycall-from-threads/32742 "2019-12-27T16:04:45Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![drhouse82](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/drhouse82/32/9806_2.png) [@drhouse82](https://discourse.julialang.org/u/drhouse82)\
**Post date:** [December 27, 2019, 4:04pm UTC](https://discourse.julialang.org/t/using-pycall-from-threads/32742/1 "2019-12-27T16:04:45Z")

</div>

I have a potentially stupid question:  
Is it possible to use pycall / pyplot from several threads at the same time?

I would guess it is not, but I want to be sure… (I could imagine having a python instance per thread so that this could work?)

Anyways, this code (where I try to save existing figures in parallel)

```julia
using PyPlot
pygui(true)

figs=[]
for index in 1:10
    fig = plt.figure()
    plt.plot(rand(10))
    push!(figs,fig)
end

Threads.@threads for index in 1:length(figs)
    println("Thread #"*string(Threads.threadid())*" saves image "*string(index))
    fig = figs[index]
    fig.savefig("image_"*string(index)*".png")
end

```

throws an exception:

```julia
Fatal Python error: GC object already tracked

Thread 0x00001018 (most recent call first):

```

Is there a way around this?  
It appears unrelated to file I/O, also happens if I try to manipulate a figure from threads.  
(Of course, in my real example the saving of the figures takes at least 10s of seconds, otherwise I wouldnt care…)

---

<div class="post-metadata">

**Author:** ![ihnorton](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ihnorton/32/26_2.png) [@ihnorton](https://discourse.julialang.org/u/ihnorton)\
**Post date:** [December 27, 2019, 5:14pm UTC](https://discourse.julialang.org/t/using-pycall-from-threads/32742/2 "2019-12-27T17:14:41Z")

</div>

There has been some discussion in the Python community about supporting “sub-interpreters”, see:

> **[Subinterpreter support for Python \[LWN.net\]](https://lwn.net/Articles/754162/)**
>
> Eric Snow kicked off the 2018 edition of
> the Python Language Summit with a look at getting a better story for
> multicore Python by way of subinterpreters. Back in 2015, we looked at his efforts at that point; things
> have been progressing since. ...

See below for a demo of loading multiple interpreters in the same process, using `dlmopen` to provide namespace isolation:

[https://gist.github.com/dutc/eba9b2f7980f400f6287](https://gist.github.com/dutc/eba9b2f7980f400f6287)

A similar approach could be implemented in Julia. I don’t know if PyCall makes assumptions about global state on the Julia side, but some level of refactoring would likely be necessary.
