Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Julia Tasks and Concurrency

Julia Tasks and Concurrency

A Task (also called a coroutine) is Julia's lightweight unit of execution that can be flexibly paused and resumed between computations, and is the foundation of Julia's concurrent programming.

Julia supports the following kinds of concurrent and parallel programming:

Category Description
Asynchronous tasks (coroutines) Task pause/resume, suitable for IO-intensive scenarios
Multithreading Multiple Tasks running simultaneously on multiple CPU threads, sharing memory
Distributed computing Multiple Julia processes cooperate, each with its own independent memory
GPU computing Run Julia code on the GPU via packages such as CUDA.jl

This chapter introduces the most commonly used coroutines and multithreading, with only a brief note on distributed computing.


Task Basics

The @task macro wraps a piece of code into a Task, which has not run yet; calling schedule() starts its execution:

Example

Create a task (not yet running)

julia

t = @task begin

           sleep

(

1

)

           

println

(

"done"

)

       

end

Task

(

runnable

)

@0x00007f13a40c0eb0

Schedule execution; schedule returns immediately

julia

schedule

(

t

)

;

wait blocks until the task completes

julia

wait

(

t

)

;

done

In practice the Threads.@spawn macro is more commonly used; it creates a task and immediately schedules it:

Example

julia

t = Threads.@

spawn

begin

           sleep

(

1

)

           

println

(

"done"

)

       

end

Task

(

runnable

)

@0x00007f13a40c11c0

fetch(t) waits for the task to complete and returns its result:

Example

julia

t = Threads.@

spawn

1

1

Task

(

runnable

)

@0x00007f13a40c13c0

julia

fetch

(

t

)

2

@sync waits for a group of tasks

The code block wrapped by @sync blocks until all tasks within it have finished:

Example

julia

@sync begin

           Threads.@

spawn

begin

               sleep

(

1

)

               

println

(

"Task 1 completed"

)

           

end

           Threads.@

spawn

begin

               sleep

(

0.5

)

               

println

(

"Task 2 completed"

)

           

end

       

end

Task

2

Complete

Task

1

Complete


Channel: Communication Between Tasks

A Channel is a first-in-first-out (FIFO) queue that lets multiple tasks safely pass data:

Example

Create a channel with capacity 32 that holds Int

julia

chnl = Channel

{

Int

}

(

32

)

;

put! puts data in

julia

put

!

(

chnl,

1

)

;

julia

put

!

(

chnl,

2

)

;

take! takes data out

julia

take

!

(

chnl

)

1

julia

take

!

(

chnl

)

2

Key behaviors of Channel:

Below is a classic producer-consumer example: 4 worker tasks take jobs from the jobs channel and write results into the results channel:

Producer-Consumer Channel Model Diagram

Example

using

Base.

Threads

jobs channel: produces jobs; results channel: collects results

const

jobs = Channel

{

Int

}

(

32

)

;

const

results = Channel

{

Tuple

}

(

32

)

;

function

do_work

(

)

   

A for loop over a channel keeps taking values until the channel is closed

   

for

job_id

in

jobs

        exec_time = rand

(

)

        sleep

(

exec_time

)

                   

Simulate real work taking time

        put

!

(

results,

(

job_id, exec_time

)

)

 

Write back the result

   

end

end

function

make_jobs

(

n

)

   

for

i

in

1

:n

        put

!

(

jobs, i

)

   

end

   

close

(

jobs

)

   

Close the jobs channel after all tasks are sent

end

n =

4

errormonitor

(

Threads.@

spawn

make_jobs

(

n

)

)

;

   

Produce tasks

for

i

in

1

:

4

                                 

Start 4 worker tasks

    errormonitor

(

Threads.@

spawn

do_work

(

)

)

end

@elapsed

while

n

0

                         

Collect results

    job_id, exec_time = take

!

(

results

)

   

println

(

"$job_id completed in $(round(exec_time; digits=2)) seconds"

)

   

global

n -=

1

end

1

Completed in

0.04

Second

4

Completed in

0.5

Second

2

Completed in

0.56

Second

3

Completed in

0.73

Second

Tip:errormonitor(t) prints error information when a task throws an exception, which is much better than silent failure; it is recommended to wrap all @spawn calls with it.


Multithreading

Starting Multithreading

Before Julia 1.10 the default was single-threaded; you can specify the number of threads with the -t flag or an environment variable:

$ julia --threads 4

# 或者

$ export JULIA_NUM_THREADS=4

$ julia

Use Threads.nthreads() to see the number of available threads:

Example

julia

Threads.

nthreads

(

)

4

julia

Threads.

threadid

(

)

   

Which thread the current code is running on

1

@threads parallel loop

Putting Threads.@threads in front of a for loop distributes the iteration range across multiple threads for parallel execution:

Example

julia

a = zeros

(

10

)

;

julia

Threads.@threads

for

i =

1

:

10

           a

[

i

]

= Threads.

threadid

(

)

       

end

julia

a      

Each element records which thread wrote it

10

-element

Vector

{

Float64

}

:

 

1.0

 

1.0

 

1.0

 

2.0

 

2.0

 

2.0

 

3.0

 

3.0

 

4.0

 

4.0

Data race warning:Multiple threads writing to the same variable in parallel produce wrong results, which is the most common pitfall in concurrent programming:

Incorrect example: data race

julia

function

sum_multi_bad

(

a

)

           s =

0

           Threads.@threads

for

i

in

a

               s += i    

Multiple threads read and write s at the same time; the result is unpredictable!

           

end

           s

       

end

sum_multi_bad

(

generic

function

with

1

method

)

julia

sum_multi_bad

(

1

:

1

_000_000

)

   

The correct answer should be 500000500000

62501142778

The correct approach is to split into chunks and sum each independently (mutually independent, no contention), then merge:

Correct Example

julia

function

sum_single

(

a

)

           s =

0

           

for

i

in

a

               s += i

           

end

           s

       

end

sum_single

(

generic

function

with

1

method

)

julia

function

sum_multi_good

(

a

)

           

Split the array into chunks by the number of threads, sum each chunk independently

           chunks = Iterators.

partition

(

a, cld

(

length

(

a

)

, Threads.

nthreads

(

)

)

)

           tasks =

map

(

chunks

)

do

chunk

               Threads.@

spawn

sum_single

(

chunk

)

           

end

           chunk_sums = fetch.

(

tasks

)

           

return

sum_single

(

chunk_sums

)

     

Merge the chunk results

       

end

sum_multi_good

(

generic

function

with

1

method

)

julia

sum_multi_good

(

1

:

1

_000_000

)

500000500000

Protect Shared Data with Locks

When multiple threads modify shared data, use ReentrantLock to ensure only one thread accesses it at a time:

Example

julia

my_lock = ReentrantLock

(

)

;

julia

my_variable =

[

1

,

2

,

3

]

;

@lock macro: executes an expression while holding the lock and unlocks automatically afterward

julia

@lock my_lock my_variable

[

1

]

=

100

100

Equivalent functional form

julia

lock

(

my_lock

)

do

           my_variable

[

1

]

=

100

       

end

100

Atomic Operations

For accumulating simple numeric values, atomic operations are more efficient than locks:

Example

julia

acc = Threads.

Atomic

{

Int64

}

(

0

)

Base.

Threads

.

Atomic

{

Int64

}

(

0

)

julia

@threads

for

i

in

1

:

1000

           Threads.

atomic_add

!

(

acc,

1

)

       

end

julia

acc

[

]

1000


Typical Scenarios for Asynchronous Programming

The greatest advantage of coroutines is IO-intensive scenarios: while waiting on the network or disk, the CPU is yielded to other tasks, so code that looks sequential actually runs concurrently:

Example

using

Sockets

Connect to three websites concurrently; the total time is roughly that of the slowest one, not the sum of the three

julia

@sync

for

hostname

in

(

"google.com"

,

"github.com"

,

"julialang.org"

)

           Threads.@

spawn

begin

               conn = connect

(

hostname,

80

)

               

write

(

conn,

"GET / HTTP/1.1\r\nHost:$(hostname)\r\n\r\n"

)

               readline

(

conn, keep=

true

)

               

println

(

"Finished connecting $(hostname)"

)

           

end

       

end

Finished connecting google.

com

Finished connecting julialang.

org

Finished connecting github.

com

Rule of thumb:For IO-intensive work (network, disk, sleep), @spawn coroutines are enough; for CPU-intensive work needing true parallelism, use @threads or @spawn and make sure Julia is started with multiple threads.