L1VM - thread in function

Here I show how to split a function into two new threads. That’s right: there will run two threads inside a function. IMHO this is a “Mission Impossible” in other programming languages. This is possible in Brackets, because we just need a label to jump to start a new thread. If this label is in the caller thread, then it starts the new thread inside.

Here is a full example:

// hello-thread-new.l1com
// Brackets - Hello world! threads in main function
//
// This is an exammple how to launch threads using the new compiler opcode "loadl".
//
#include <intr.l1h>
#include <misc-macros.l1h>
(main func)
    (set const-int64 1 zero 0)
    (set const-int64 1 one 1)
    (set int64 1 f 0)
    (set int64 1 cpu 0)
    (set string s hello_onestr "Hello world! thr 1")
    (set string s hello_twostr "Hello world! thr 2")
    (set int64 1 t1_l 0)
    (set int64 1 t2_l 0)
    (set int64 1 delay 1000)

    // set thread labels
    (:ta t1_l loadl)
    (:tb t2_l loadl)
    pull_int64_var (t1_l)
    pull_int64_var (t2_l)

    get_cpu (cpu)
    (((cpu zero ==) f =) f if)
        thread (t1_l)
        thread (t2_l)
        detime (delay)
        (:do_wait jmp)
    (endif)

    (:ta)
    (reset-reg)
    print_s (hello_onestr)
    print_n
    threadexit (zero)

    (:tb)
    (reset-reg)
    print_s (hello_twostr)
    print_n
    threadexit (zero)

    (:do_wait)
    detime (delay)
    join
    exit (zero)
(funcend)