Parallel code
x has parallel loops, parallel sections, tasks, channels, locks and atomic changes built into the language. They run on a pool of worker threads that the runtime starts the first time they're needed, one per CPU. A program that uses any of them is compiled in thread mode, like one that calls CreateThread.
These are x additions. PureBasic has threads (Thread) but not these statements. Parallel, Section, Chunk, Reduce, Lock, Atomic and the other new words are only keywords where they start one of these statements, so programs that use them as names (lock = CreateMutex(), atomic * 2, Procedure Lock(m)) work as before.
Parallel For ✅
Parallel For i = start To end [Step n] [Chunk size] [Reduce var op, ...]
...
Next
The iterations run at the same time, on as many threads as there are CPUs. They may run in any order, so each iteration should only depend on i. The loop is over once every iteration has finished.
i, and the variables first used inside the body, are the body's own: every iteration has its own, starting at 0 (or""). So is the variable of a loop inside the body.- Everything else (the procedure's other variables, main code's, globals, arrays, lists) is shared by all the threads. Reading it is fine. To change a shared variable, use
Reduce,AtomicorLock. The compiler warns (W7) when a shared variable is changed any other way. Stepmust be a constant, as inFor.start,endandiare whole numbers.BreakandProcedureReturncan't leave the loop, since the iterations are separate.Continuegoes on to the next iteration.
OpenConsole()
Global Dim squares(9)
Parallel For i = 0 To 9
squares(i) = i * i ; each iteration writes its own element
Next
For i = 0 To 9 : Print(Str(squares(i)) + " ") : Next
PrintN("")
Output:
0 1 4 9 16 25 36 49 64 81
Reduce
Reduce total + gives every thread its own total, starting from nothing (0 for +), and combines them into the real total when the loop is over. The operators are +, *, Min, Max, And, Or and Xor (the last three on whole numbers).
The iterations are cut into chunks whose size depends only on the number of iterations, and the totals of the chunks are combined in chunk order. So a Reduce over floats gives exactly the same result on every run and on any number of CPUs, unlike adding from several threads with a lock.
OpenConsole()
Procedure.s Summary(n)
Protected total.d, smallest = 1000, largest = -1000, i
Parallel For i = 1 To n Reduce total +, smallest Min, largest Max
Protected v = (i * 37) % 101 - 50
total + Sqr(i)
If v < smallest : smallest = v : EndIf
If v > largest : largest = v : EndIf
Next
ProcedureReturn StrD(total, 4) + " " + Str(smallest) + " " + Str(largest)
EndProcedure
PrintN(Summary(1000))
Output:
21097.4559 -50 50
Chunk
By default the iterations are cut into about 64 chunks. Chunk size sets how many iterations each chunk has: small chunks share uneven work out better, large ones cost less to hand out.
Parallel sections ✅
Parallel
Section
...
Section
...
EndParallel
The sections run at the same time. EndParallel waits until all of them have finished. Each section runs once, so it can set a variable of its own for the code after EndParallel to read.
OpenConsole()
Global words, letters, lines
text$ = "one two three" + #LF$ + "four five"
Parallel
Section
words = CountString(ReplaceString(text$, #LF$, " "), " ") + 1
Section
letters = Len(ReplaceString(ReplaceString(text$, " ", ""), #LF$, ""))
Section
lines = CountString(text$, #LF$) + 1
EndParallel
PrintN(Str(words) + " words, " + Str(letters) + " letters, " + Str(lines) + " lines")
Output:
5 words, 19 letters, 2 lines
Lock ✅
Lock [mutex]
...
EndLock
One thread at a time runs the body. Without a mutex, the block has a mutex of its own, made the first time. Lock m uses a mutex from CreateMutex. The mutex is unlocked however the body is left, including by Break, Continue and ProcedureReturn.
OpenConsole()
Global NewList found.s()
Parallel For i = 1 To 20
If i % 6 = 0
Lock ; one thread at a time changes the list
AddElement(found())
found() = Str(i)
EndLock
EndIf
Next
SortList(found(), #PB_Sort_Ascending)
ForEach found() : Print(found() + " ") : Next
PrintN("")
Output:
12 18 6
Atomic ✅
Atomic variable + value ; also - | & !
Changes a whole-number variable, array element or structure field in one step that no other thread can interrupt. It's much faster than a Lock for a counter.
OpenConsole()
Global hits, Dim perDigit(9)
Parallel For i = 0 To 9999
Atomic hits + 1
Atomic perDigit(i % 10) + i
Next
PrintN(Str(hits) + " " + Str(perDigit(0)) + " " + Str(perDigit(9)))
Output:
10000 4995000 5004000
ParallelWorkers ✅
Count = ParallelWorkers([n])
Sets how many threads Parallel For and Parallel use, counting the one that runs them, and returns the number. ParallelWorkers(0) goes back to one per CPU. ParallelWorkers() only returns the number. With 1, everything runs on the calling thread, in order, which helps when debugging. The results are the same either way.
Tasks: Spawn and Await ✅
Task = Spawn Procedure(arguments)
Result = Await(Task) ; AwaitD(Task) for a float result, AwaitS(Task) for a string
Done = TaskDone(Task)
Spawn starts one of the program's procedures on a thread of its own and carries on straight away. The arguments are worked out first and copied, strings included, so the caller can change its variables afterwards. Await waits for the procedure to return and returns its result. Every task is awaited once: Await also frees it. TaskDone returns non-zero once the task has finished, without waiting.
A procedure with Array, List or Map parameters can't be spawned. Pass a pointer, or use a global or a channel.
OpenConsole()
Procedure.i CountPrimes(limit)
Protected n, d, count
For n = 2 To limit
d = 2
While d * d <= n And n % d
d + 1
Wend
If d * d > n : count + 1 : EndIf
Next
ProcedureReturn count
EndProcedure
Procedure.s Shout(word$, times)
ProcedureReturn RSet("", times, "!") + UCase(word$)
EndProcedure
small = Spawn CountPrimes(1000) ; both run while the main program goes on
large = Spawn CountPrimes(20000)
name = Spawn Shout("tasks", 3)
PrintN(Str(Await(small)) + " " + Str(Await(large)) + " " + AwaitS(name))
Output:
168 2262 !!!TASKS
Channels ✅
NewChannel name.type([capacity])
Ok = SendChannel(name(), value)
Value = ReceiveChannel(name())
CloseChannel(name())
Count = ChannelSize(name())
ForEach name() ... Next
A channel passes values from one thread to another, in order. It's declared like a list, carries numbers, pointers or strings, and holds up to capacity values (16 by default).
SendChannelwaits while the channel is full. It returns 1, or 0 if the channel is closed.ReceiveChannelwaits until there is a value and returns it. Once the channel is closed and empty it returns 0 (or"") at once.CloseChannelmeans no more values will come. Values already in the channel can still be received.ForEach name()receives values until the channel is closed and empty. Inside the loopname()is the value just received. Several threads can runForEachon the same channel: each value goes to one of them.ChannelSizereturns how many values are waiting.
Declare channels in main code or with Global. A channel used by procedures (tasks, for example) needs Global, like a list.
OpenConsole()
Global NewChannel jobs.s(4)
Global NewChannel lengths.i()
Procedure.i Worker(id)
Protected handled
ForEach jobs() ; until jobs is closed and empty
SendChannel(lengths(), Len(jobs()))
handled + 1
Next
ProcedureReturn handled
EndProcedure
a = Spawn Worker(1)
b = Spawn Worker(2)
For i = 1 To 12
SendChannel(jobs(), "job number " + Str(i))
Next
CloseChannel(jobs())
handled = Await(a) + Await(b)
CloseChannel(lengths())
ForEach lengths() : total + lengths() : Next
PrintN(Str(handled) + " jobs, " + Str(total) + " characters")
Output:
12 jobs, 147 characters
How it runs
- The workers are started the first time a parallel statement runs, and wait for work after that.
- A
Parallel FororParallelinside a body that is already running on the pool (for example in a procedure the body calls) runs on its own thread, in order. So does one started while another thread's parallel statement is using the pool. - On targets without threads (bare metal, planned), everything runs in order, with the same results.
Each task runs on a thread of its own, so a task can wait for a channel or for another task without holding anything else up.
Not done yet
- A
Parallel FororParallelwritten directly inside another one's body. - Channels of structures, channels declared inside procedures, and channels as procedure parameters.