task_local_storage(body, symbol, value)

task_local_storage(body, symbol, value)

Call the function body with a modified task-local storage, in which value is assigned to symbol; the previous value of symbol, or lack thereof, is restored afterwards. Useful for emulating dynamic scoping.

Examples

# Assign a value to a symbol in the current task's task-local storage.
function task_local_storage(symbol, value)
    Base.task_local_storage()[symbol] = value
end

Examples:

  1. Assign a value to a symbol:

    julia> task_local_storage(:name, "John")
    "John"

    This example assigns the value "John" to the symbol :name in the current task's task-local storage.

  2. Update the value of a symbol:

    julia> task_local_storage(:age, 25)
    25
    
    julia> task_local_storage(:age, 30)
    30

    It assigns the value 25 to the symbol :age and then updates it to 30 in the task-local storage.

  3. Access the value of a symbol:

    julia> task_local_storage(:name, "Alice")
    "Alice"
    
    julia> task_local_storage(:name)
    "Alice"

    This example assigns the value "Alice" to the symbol :name and then retrieves its value from the task-local storage.

Common mistake example:

julia> task_local_storage("name", "Bob")
ERROR: MethodError: no method matching task_local_storage(::String, ::String)

In this example, a string "name" is used as the symbol for task-local storage. However, the symbol argument should be a symbol type (Symbol) and not a string. Make sure to use the correct data type for the symbol argument.

See Also

:@async, :@schedule, :@task, Condition, consume, interrupt, istaskdone, istaskstarted, lock, notify, ReentrantLock, schedule, Task, task_local_storage, unlock, wait, yield, yieldto,

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: