I want to synchronize between threads by using notify&wait
as in the example MWE, in which nthreads()=3
. Each thread executes for-loop
and while-loop
inside it. It is similar to what mentioned in Can the threads synchronized by channel?, but with different way of synchronization primitives.
In the MWE, I want to let the threads execute in order:
1- All enter the while-loop together. By using condition_main
so thread-1 synchronize with 2&3
.
2- At each iteration of the while-loop, thread-1 sets status = true
and notify other threads to inter the while-loop. In each iteration of the while-loop
, the first thread executes Block-1
and notify other threads to print their statements via condition_main
, and wait until they finish by using condition_threads
to move to the following iteration of the while-loop.
3- When status = false
, all threads move to the following iteration of the for-loop.
Please note, I dont need to use sleep
function to avoid killing the performance.
function NN()
condition_main = Condition()
condition_threads = [Condition() for _ in 1:nthreads()-1]
status = true
@threads for _ in 1:nthreads()
if threadid() == 1
@async begin
for t in 1:2
iter = 0
status = true
notify(condition_main)
while status
# Start Block-1
println("Iteration $t Thread $(threadid()) Update status")
iter += 1
if iter == 2
status = false
end
# Block-1
notify(condition_main)
wait.(condition_threads)
end # while status
end # for t in 1:2
end # @async begin
else # if threadid() == 1
@async begin
for tt in 1:2
wait(condition_main)
while status
wait(condition_main)
println("Iteration $tt Thread $(threadid()) Execution")
notify(condition_threads[threadid()-1])
end #while status
end # for t in 1:2
end #@async begin
end # if threadid() == 1
end # @threads for _ in 1:nthreads()
return nothing
end
NN()
I expect the results to show as below:
Iteration 1 Thread 1 Update status
Iteration 1 Thread 2 Execution
Iteration 1 Thread 3 Execution
Iteration 1 Thread 1 Update status
Iteration 1 Thread 2 Execution
Iteration 1 Thread 3 Execution
Iteration 2 Thread 1 Update status
Iteration 2 Thread 2 Execution
Iteration 2 Thread 3 Execution
Iteration 2 Thread 1 Update status
Iteration 2 Thread 2 Execution
Iteration 2 Thread 3 Execution
However, I am having only as below because it is freezes. Any help please?
Iteration 1 Thread 1 Update status