Thread
Threads run procedures at the same time as the main program. Mutexes keep them from changing shared data at the same moment, and semaphores let one thread wait for another.
A program that calls CreateThread is compiled in thread mode (#PB_Compiler_Thread is 1): strings are counted with atomic instructions, so threads can share them, and the runtime's memory allocator takes a lock. Programs without threads don't pay for this. The compiler option -thread turns thread mode on without CreateThread, for example for a library.
Lists, maps, arrays and files shared between threads need a mutex, as in PureBasic. Each thread has its own copy of a Threaded variable.
For splitting work across all the CPUs, x also has parallel statements built in: Parallel For (with Reduce), Parallel sections, Lock and Atomic. They use a pool of worker threads, so they cost far less to start than a thread each.
CreateThread ✅
Thread = CreateThread(@Procedure(), Value)
Starts a thread that runs Procedure(Value). The procedure takes one integer or pointer parameter. The thread ends when the procedure returns.
Returns the thread, for WaitThread, IsThread and ThreadID, or 0 if it couldn't be started.
Global Dim results(3)
Procedure Square(n)
results(n) = n * n
EndProcedure
OpenConsole()
Dim threads(3)
For i = 0 To 3
threads(i) = CreateThread(@Square(), i)
Next
For i = 0 To 3
WaitThread(threads(i))
Next
PrintN(Str(results(0)) + " " + Str(results(1)) + " " + Str(results(2)) + " " + Str(results(3)))
Output:
0 1 4 9
WaitThread ✅
Result = WaitThread(Thread [, Timeout])
Waits for the thread to end, or at most Timeout milliseconds.
Returns non-zero if the thread has ended, 0 if the time ran out first.
IsThread ✅
Result = IsThread(Thread)
Returns non-zero while the thread is running.
ThreadID ✅
Id = ThreadID(Thread)
Returns the operating system's number for the thread.
CreateMutex ✅
Mutex = CreateMutex()
FreeMutex(Mutex)
A mutex lets one thread at a time into a part of the program. FreeMutex frees it once no thread uses it.
LockMutex, UnlockMutex, TryLockMutex ✅
LockMutex(Mutex)
UnlockMutex(Mutex)
Result = TryLockMutex(Mutex)
LockMutex waits until no other thread has the mutex, then takes it. UnlockMutex gives it back. A thread can lock a mutex it already has again, and must unlock it as many times. TryLockMutex takes the mutex only if that needs no wait, and returns non-zero if it did.
Global total, lock = CreateMutex()
Procedure Add(n)
Protected i
For i = 1 To n
LockMutex(lock)
total + 1 ; one thread at a time
UnlockMutex(lock)
Next
EndProcedure
OpenConsole()
a = CreateThread(@Add(), 50000)
b = CreateThread(@Add(), 50000)
WaitThread(a)
WaitThread(b)
PrintN(Str(total))
Output:
100000
CreateSemaphore ✅
Semaphore = CreateSemaphore([InitialCount])
FreeSemaphore(Semaphore)
A semaphore is a counter that threads can wait on. It starts at InitialCount (default 0).
SignalSemaphore, WaitSemaphore, TrySemaphore ✅
SignalSemaphore(Semaphore)
WaitSemaphore(Semaphore)
Result = TrySemaphore(Semaphore)
SignalSemaphore adds 1. WaitSemaphore waits until the count is above 0, then takes 1 off. TrySemaphore takes 1 off only if that needs no wait, and returns non-zero if it did.
A queue that one thread fills and another empties, with a mutex around the list and a semaphore counting what is in it:
Global NewList queue.s()
Global lock = CreateMutex(), items = CreateSemaphore()
Procedure Consumer(count)
Protected i, item$
For i = 1 To count
WaitSemaphore(items) ; until there is something to take
LockMutex(lock)
FirstElement(queue())
item$ = queue()
DeleteElement(queue())
UnlockMutex(lock)
PrintN("got " + item$)
Next
EndProcedure
OpenConsole()
t = CreateThread(@Consumer(), 3)
For i = 1 To 3
LockMutex(lock)
LastElement(queue())
AddElement(queue())
queue() = "item " + Str(i)
UnlockMutex(lock)
SignalSemaphore(items)
Next
WaitThread(t)
Output:
got item 1
got item 2
got item 3
Threaded variables ✅
Threaded name[.type] [, ...]
Threaded Dim name[.type](size [, size2])
Threaded NewList name[.type]()
Threaded NewMap name[.type]([slots])
A Threaded variable is global, but each thread has its own, starting at 0 (or an empty string). It suits things like a thread's number or its last error.
A Threaded array, list or map is also one per thread. A new thread starts with its own array of the declared size (all zero) and its own empty list or map, and frees them when it ends, along with its Threaded strings. The main thread makes its own when it runs the declaration, as with Global. Since the other threads never run the declaration, an array's sizes and a map's slots must be constants. A thread can ReDim its own array.
Threaded id
Global lock = CreateMutex()
Global NewList seen.i()
Procedure Work(n)
id = n
Delay(10) ; the other threads set their own id meanwhile
LockMutex(lock)
AddElement(seen())
seen() = id
UnlockMutex(lock)
EndProcedure
OpenConsole()
Dim threads(2)
For i = 0 To 2
threads(i) = CreateThread(@Work(), i + 1)
Next
For i = 0 To 2
WaitThread(threads(i))
Next
SortList(seen(), #PB_Sort_Ascending)
ForEach seen()
Print(Str(seen()) + " ")
Next
PrintN("main: " + Str(id))
Output:
1 2 3 main: 0
Each thread collects its own results in a Threaded list, then hands over the total:
Threaded NewList found.i()
Global lock = CreateMutex()
Global Dim totals(2)
Procedure Multiples(n)
Protected i
For i = 1 To 20
If i % n = 0
AddElement(found()) ; this thread's own list
found() = i
EndIf
Next
LockMutex(lock)
totals(n - 2) = ListSize(found())
UnlockMutex(lock)
EndProcedure
OpenConsole()
Dim threads(2)
For i = 0 To 2
threads(i) = CreateThread(@Multiples(), i + 2)
Next
For i = 0 To 2
WaitThread(threads(i))
Next
PrintN(Str(totals(0)) + " " + Str(totals(1)) + " " + Str(totals(2)) + " main: " + Str(ListSize(found())))
Output:
10 6 5 main: 0
Notes. Every thread starts in the runtime, which makes its Threaded collections, calls the procedure, then frees them. On Windows, threads, mutexes and semaphores are the system's. On Linux they are made with clone and futexes, and a thread has a 1 MB stack. A Threaded variable is reached through the thread's own block (Windows TLS, or the fs register on Linux), which costs one or two extra instructions.
ParallelWorkers ✅ (x addition)
Count = ParallelWorkers([n])
How many threads Parallel For and Parallel use. See there.
Not done yet
KillThread,PauseThread,ResumeThread,ThreadPriority.Threadedarrays with sizes that aren't constants.