Hello! I have this experimental code:
import strformat
import os
import times
type
Student* = object
name: string
num: int
proc sayHi(student: Student) {.thread, nimcall.} =
echo fmt"Hello {student.name}! Your number: {student.num}"
sleep(1_250)
proc main() =
var threads: array[4, Thread[int]]
var students: seq[Student]
var names = @["Ivan", "Maxim", "Maikl", "Alex"]
for i in 0..3:
var student: Student
student.name = names[i]
student.num = i
students.add(student)
var start = cpuTime()
for i in threads.low..threads.high:
threads[i].createThread(sayHi, students[i])
joinThreads(threads)
echo cpuTime() - start
main()
But when i trying to compile it, have next error:
Error: type mismatch: got <Thread[system.int], proc (student: Student){.nimcall, gcsafe, locks: 0.}, Student>
but expected one of:
proc createThread[TArg](t: var Thread[TArg];
tp: proc (arg: TArg) {.thread, nimcall.}; param: TArg)
first type mismatch at position: 2
required type for tp: proc (arg: TArg){.nimcall, gcsafe.}
but expression 'sayHi' is of type: proc (student: Student){.nimcall, gcsafe, locks: 0.}
1 other mismatching symbols have been suppressed; compile with --showAllMismatches:on to see them
What im doing wrong? Thanks for helping.Well the error message is complaining that you're trying to run a Thread[int] with a proc (_: Student) and a value of type Student. The generic type of the thread needs to match the argument.
Apart from that I believe the threads variable has to be global.
FML. You absolutely right about type in Thread. Big tnx! I skipped it for my example xd
Hello Ivan! Your number: 0
Hello Maxim! Your number: 1
Hello Maikl! Your number: 2
Hello Alex! Your number: 3
1.267
About edit: i experimented with for loops. We measure time for running without threading and with that. Just for that cause i used CpuTime() :)
If you have 8 threads and each spend a second to do something, the CPU time is 8s. What you're interested in is the wall time / elapsed time, use getMonotime() for this.