Skip to content

Commit

Permalink
Added option to set global thread number during runtime
Browse files Browse the repository at this point in the history
  • Loading branch information
tsoj committed Apr 26, 2024
1 parent 3924137 commit cb653ee
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/malebolgia.nim
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ type
data: array[FixedChanSize, PoolTask]

var
thr: array[ThreadPoolSize-1, Thread[void]] # -1 because the main thread counts too
thr: seq[Thread[void]]
chan: FixedChan
globalStopToken: Atomic[bool]
busyThreads: Atomic[int]
Expand Down Expand Up @@ -153,10 +153,13 @@ proc worker() {.thread.} =
# but mark it as completed either way!
taskCompleted item.m[]

proc setup() =
proc malebolgiaSetup*(numThr: int) =
doAssert numThr > 0, "Malebolgia must be initialized with a thread pool size of at least one"
doAssert thr.len == 0, "Malebolgia can only be initialized once"
initCond(chan.dataAvailable)
initCond(chan.spaceAvailable)
initLock(chan.L)
thr.setLen(numThr - 1) # -1 because the main thread counts too
for i in 0..high(thr): createThread[void](thr[i], worker)

proc panicStop*() =
Expand All @@ -168,7 +171,10 @@ proc panicStop*() =
deinitLock(chan.L)

proc shouldSend(master: var Master): bool {.inline.} =
master.activeProducer or busyThreads.load(moRelaxed) < ThreadPoolSize-1
{.cast(gcsafe).}:
let numThr = thr.len
doAssert numThr > 0, "Malebolgia must be initialized first"
master.activeProducer or busyThreads.load(moRelaxed) < numThr

template spawnImplRes[T](master: var Master; fn: typed; res: T) =
if stillHaveTime(master):
Expand Down Expand Up @@ -254,6 +260,6 @@ template awaitAll*(master: var Master; body: untyped) =
waitForCompletions(master)

when not defined(maleSkipSetup):
setup()
malebolgiaSetup(ThreadPoolSize)

include malebolgia / masterhandles
27 changes: 27 additions & 0 deletions tests/tasymmetric_load.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import malebolgia

import std/[os, atomics]

malebolgiaSetup(numThr = 20)

var
threadpool = createMaster(activeProducer = true)
busyThreads: Atomic[int]
busyThreads.store 0

let mainThreadId = getThreadId()

proc findStartPositionsAndPlay() =
atomicInc busyThreads
echo "Started. Busy threads: ", busyThreads.load

sleep(1000)
if getThreadId() == mainThreadId:
sleep(10_000)

atomicDec busyThreads
echo "Finished. Busy threads: ", busyThreads.load

threadpool.awaitAll:
for i in 1 .. 10000:
threadpool.spawn findStartPositionsAndPlay()

0 comments on commit cb653ee

Please sign in to comment.