← Back to lessons

45 Thread Variables

Hard

You can use ThreadLocal in the core package to create and use thread local variables.each thread can safely access its own thread local variables without being affected by other threads.

ThreadLocal variable initialization. .get() returns Option<T>.

Set value of variable a to 123. Print that value. Wait for the second thread to set value of a. Print the same unchanged value.

Change value of a during the time first thread is running.

As we can see, truly, the variable a is local to each thread.

thread_variables.cj
import std.sync.*
import std.time.*

main() {
    let a = ThreadLocal<Int64>()
    let thread1 = spawn {
        a.set(123)
        println("Local variable of thread1 is ${a.get().getOrThrow()}")
        sleep(Duration.second)
        println("Local variable of thread1 is ${a.get().getOrThrow()}")
    }

    let thread2 = spawn {
        a.set(290)
        println("Local variable of thread2 is ${a.get().getOrThrow()}")
    }

    thread1.get()
    thread2.get()
}

/* Sample Output:
Local variable of thread1 is 123
Local variable of thread2 is 290
Local variable of thread1 is 123
*/