added threading examples

This commit is contained in:
Stefan Salewski 2020-07-17 09:16:49 +02:00
commit 06dd5e6ed9
5 changed files with 243 additions and 0 deletions

View file

@ -19,6 +19,7 @@ nim c listview.nim
nim c menubar.nim
nim c overlay_tree1.nim
nim c simpledrawingarea.nim
nim c spinbutton.nim
nim c sourceview_test.nim
nim c t0.nim
nim c vte.nim

View file

@ -19,6 +19,7 @@ nim c --gc:arc listview.nim
nim c --gc:arc menubar.nim
nim c --gc:arc overlay_tree1.nim
nim c --gc:arc simpledrawingarea.nim
nim c --gc:arc spinbutton.nim
nim c --gc:arc sourceview_test.nim
nim c --gc:arc t0.nim
nim c --gc:arc vte.nim

47
examples/gtk3/thread1.nim Normal file
View file

@ -0,0 +1,47 @@
# https://nim-lang.org/docs/channels.html
# nim c --threads:on --gc:arc -r thread1.nim
import gintro/[gtk, glib, gobject, gio]
from os import sleep
var channel: Channel[int]
var workThread: system.Thread[void]
proc workProc =
var countdown {.global.} = 25
while countdown > 0:
sleep(1000)
dec(countdown)
channel.send(countdown)
proc updateGUI(b: Button): bool =
let msg = channel.tryRecv()
if msg.dataAvailable:
b.label = $msg.msg
if msg.msg == 0:
workThread.joinThread
channel.close
return SOURCE_REMOVE
return SOURCE_CONTINUE
proc buttonClicked (b: Button) =
b.label = utf8Strreverse(b.label, -1)
proc activate (app: Application) =
let window = newApplicationWindow(app)
window.title = "Countdown"
window.defaultSize = (250, 50)
let button = newButton("Click Me")
window.add(button)
button.connect("clicked", buttonClicked)
window.showAll
channel.open
createThread(workThread, workProc)
discard timeoutAdd(1000 div 60, updateGUI, button)
proc main =
let app = newApplication("org.gtk.example")
connect(app, "activate", activate)
discard app.run
main()

38
examples/gtk3/thread2.nim Normal file
View file

@ -0,0 +1,38 @@
# nim c --threads:on --gc:arc -r thread2.nim
import gintro/[gtk, glib, gobject, gio]
from os import sleep
var workThread: system.Thread[void]
var button: Button
proc idleFunc(i: int): bool =
button.label = $i
return SOURCE_REMOVE
proc workProc =
var countdown {.global.} = 25
while countdown > 0:
sleep(1000)
dec(countdown)
idleAdd(idleFunc, countdown)
proc buttonClicked(button: Button) =
button.label = utf8Strreverse(button.label, -1)
proc activate(app: Application) =
let window = newApplicationWindow(app)
window.title = "Countdown"
window.defaultSize = (250, 50)
button = newButton("Click Me")
window.add(button)
button.connect("clicked", buttonClicked)
window.showAll
createThread(workThread, workProc)
proc main =
let app = newApplication("org.gtk.example")
connect(app, "activate", activate)
discard app.run
main()