NiGui icon indicating copy to clipboard operation
NiGui copied to clipboard

Please help me, how can I terminate a thread in main UI thread?

Open zhouhm opened this issue 10 months ago • 2 comments

import nigui
import os
import strutils, strformat
import std/deques

var
  window: Window
  container: LayoutContainer
  button_start: Button
  thread: Thread[void]

var
  commChan: Channel[string]

commChan.open()

var
  p: int
  s: string

var queue = initDeque[int]()

app.init()

window = newWindow("NiGui Example")

container = newLayoutContainer(Layout_Vertical)
container.padding = 10
window.add(container)

button_start = newButton("Start thread")
container.add(button_start)


var textArea = newTextArea()
# Create a multiline text box.
# By default, a text area is empty and editable.


proc start() =
  {.gcsafe.}:
    let tried = commChan.tryRecv()
    if tried.dataAvailable:
      echo "我收到停止的信号了"
      echo tried.msg

    p += 1
    s = fmt("Pass {p:5d}")
    #textArea.text = s
    queue.addFirst(1)
    sleep(30000)

    p += 1
    s = fmt("Pass {p:5d}")
    #textArea.text = s
    queue.addFirst(2)
    sleep(30000)

    p += 1
    s = fmt("Pass {p:5d}")
    #textArea.text = s
    queue.addFirst(99)
    

button_start.onClick = proc(event: ClickEvent) =
  container.remove(button_start)
  
  container.add(textArea)   # Add the text area to the container.
  
  createThread(thread, start)
  echo "我爱你塞北的雪"
  while true:
    app.processEvents()
    if len(queue) > 0:
      let signal = queue.popLast
      if signal == 99:
        textArea.text = "运行结束"
        break
      elif signal == 1:
        textArea.text = "第一次更新888"
      elif signal == 2:
        textArea.text = "第二次更新999"

    app.sleep(100)
       
window.onCloseClick = proc(event: CloseClickEvent) =
  commChan.send("stop")
  `=destroy`(thread)
  window.dispose()


window.show()
app.run()

When I click the close windows I want to terminate the start thread. but I found when I click the close the start thread still running

zhouhm avatar Apr 26 '24 07:04 zhouhm

As I understand it, this is not related to NiGui. I suggest to look at https://forum.nim-lang.org/t/7092, or ask in the Nim Discord. The idea to send a "stop" signal to the thread could work too, but the thread needs to read the message and react to it. As I understand the code, it stays in one of the 30 seconds sleep calls.

simonkrauter avatar Apr 27 '24 13:04 simonkrauter

Thank you for your tip. I will study the thread of nim carefully. I am a newbie using nim. I want to use nim and the NiGui library you developed to develop a management console for me.

zhouhm avatar Apr 28 '24 00:04 zhouhm