Servus,
I'm building an multithreading app with malebolgia. I'd like to spawn a proc called 'workerThread' and pass an array called 'arr' to it. The 'workerThread' declares the formal parameter as 'workerArr: openArray[int]'. Doing like that I can't modify the content of 'workerArr' what I want to do. 'workerArr[0] = 8' won't be accepted by the compiler. Here my question: Is there an efficient way to make it happen?
The solution I have in mind is the following: 'spawn workerThread(arr)' copies the content of 'arr' on the stack of 'workerThread'. That should be 'workerArr' in the 'workerThread' and behave just like a locally declared array in 'workerThread'.
type Buffer[T] = tuple[p: ptr UncheckedArray[T], len: int]
proc worker(buf: Buffer) {.thread.} =
for i in 0..<buf.len:
buf.p[i] = default(buf.T) # whatever
var here: array[2, byte]
var thread: Thread[Buffer[byte]]
thread.createThread(worker, (cast[ptr UncheckedArray[byte]](addr here[0]), here.len))
thread.joinThread()
echo here
You cannot pass openArray, but you can pass an unchecked array whose lifetime you have to be careful to manage in such a way that it extends past the end of the work.