• Receive value from thread

    From Shaun Kulesa@21:1/5 to All on Mon Mar 13 08:11:18 2023
    Hello, I have code that sends a variable to a thread and then multiplies it by 2.

    How can I can I return this new variable in the thread and use it in the main thread?

    My code:

    package require Tcl 8.6
    package require Thread

    set t1 [thread::create {
    thread::wait
    set b [expr {$a * 2}]
    # return $b to the main thread
    }]

    thread::send -async $t1 "set a 2" result

    # get the result (variable $b) from the thread

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From et99@21:1/5 to Shaun Kulesa on Mon Mar 13 09:57:32 2023
    On 3/13/2023 8:11 AM, Shaun Kulesa wrote:
    Hello, I have code that sends a variable to a thread and then multiplies it by 2.

    How can I can I return this new variable in the thread and use it in the main thread?

    My code:

    package require Tcl 8.6
    package require Thread

    set t1 [thread::create {
    thread::wait
    set b [expr {$a * 2}]
    # return $b to the main thread
    }]

    thread::send -async $t1 "set a 2" result

    # get the result (variable $b) from the thread

    Once your thread script executes the thread::wait, the thread goes into the event loop waiting for thread::send calls.

    The manual warns that thread::wait should be the final statement in the script with thread::create. It's not clear (to me) what will happen when you have
    code following the thread::wait.


    What you likely want is to do this

    set t1 [thread::create {
    thread::wait
    }]

    Then,

    set breturn1 [thread::send $t1 {set a 123; set b [expr {$a * 2}] }]

    or

    thread::send -async $t1 {set a 246; set b [expr {$a * 2}] } breturn2
    vwait breturn2

    Here you send in both a and the code to compute b from a. The return value
    will be b since it is the value of the last statement in your sent script with the set statement.

    You can execute code to compute b before the thread::wait if you want. Then
    you could retrieve the value of b with:

    set t1 [thread::create {
    set b "some value"
    thread::wait
    }]
    set bval [thread::send $t1 {set b}]

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Shaun Kulesa@21:1/5 to All on Mon Mar 13 10:10:22 2023
    Thank you very much, I have one of your examples:

    package require Tcl 8.6
    package require Thread

    set t1 [thread::create {
    thread::wait
    }]

    thread::send -async $t1 {
    set a 246;
    set b [expr {$a * 2}]
    } breturn2

    vwait breturn2
    puts $breturn2

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)