Threads.@threads not working


I am running into a strange problem when I try to do multithreading over a very simple loop. I have Julia version 1.1.0 and start with 4 threads. The loop is

Threads.@threads for i in 1:N

Where the function t2() is

function t2(n::Int64)
id = Threads.threadid();print("\nn = “,n,” at thread ",id);

But when I execute :


The execution stops at

n = 3 at thread 3


I/O does not yet work inside @threads loops. Hopefully this will be fixed very soon though.

1 Like

Thank you for that information. But by I/O, did you mean reading or writing to files ? I do not do that within the body of the function t2() that I call at each iteration.


I/O includes printing.


I would be grateful if you could suggest a way around this.
Multithreading is a very basic necessity in applications with lot of data or with large matrices. The practice of splitting independent iterations over different threads / processor is also very common.


Don’t print inside your threaded loop?

Alternatively you can use locks around your printing statements, but depending upon how big the rest of your computation is the overhead there could end up swamping your runtime.

1 Like

What you could also do is have just thread 1 do all the printing, and give each other thread an array that they can push! their strings into. You can then decrease lock contention by only locking between thread 1 and thread n when operating on queue n, instead of having to lock across all 1:n threads for any print operation.

Edit: Of course, if you want your prints to happen in-order, you’ll need to get fancy with things like timestamps and/or separate thread 1-only queues to keep stuff aligned.

Edit2: I think this is also the same approach that will be used in the future by PARTR, doing all IO on a single thread.

1 Like

Thank you for the recipe. I think the problem with Threading is much deeper. I will mention it in another post.