How to plot in multiple threads?

Viewed 75

I ran into a problem with creating plots within a @threads for loop. Here is a simplified version of my code:

import Plots

function main()
    n_points::Int64=10
    n_epochs::Int64=100
    NP=100

    mkdir("test")

    lk::ReentrantLock=ReentrantLock()
    i::Int64=0

    Threads.@threads for _i in 1:n_points       
        data=rand(Float64,(n_epochs,NP)) # do some calculation here

        lock(lk)
        i+=1
        println("------------------------------------")
        println("run $i, thread $(Threads.threadid()), NP $NP")
        p=Plots.plot(1:n_epochs, data, legend = false)
        Plots.xlabel!(p,"epoch")
        Plots.ylabel!(p,"data")
        Plots.savefig(p,"./test/train_$i")
        println("...plotted")
        unlock(lk)
    end
end

main()

Using a lock this should be thread-safe. However, the tick labels in plots created from threads with threadid()!=1 are wrong: example

Am I doing something wrong or is this worth a bug report?

0 Answers
Related