put!(::Channel, value)
put!(Channel, value)
Appends an item to the channel. Blocks if the channel is full.
Examples
In the Julia programming language, the function put!(::Channel, value)
Appends an item value to the specified Channel. If the channel is full, the function blocks until space becomes available.
-
Put values into a channel:
julia> ch = Channel(3); julia> put!(ch, 10); julia> put!(ch, 20); julia> put!(ch, 30);In this example, we create a channel
chwith a capacity of 3. We then put three values (10,20, and30) into the channel usingput!. -
Blocking behavior when the channel is full:
julia> ch = Channel(2); julia> put!(ch, "apple"); julia> put!(ch, "banana"); julia> put!(ch, "orange");Here, we create a channel
chwith a capacity of 2. After putting"apple"and"banana"into the channel, the thirdput!operation blocks until space becomes available in the channel.
Common mistake example:
julia> ch = Channel(1);
julia> put!(ch, "apple");
julia> put!(ch, "banana");
ERROR: TaskFailedException:
BoundsError: attempt to access Tuple{Channel{String}} at index [2]
In this example, the channel has a capacity of 1, so it can only hold one value at a time. When attempting to put "banana" into the channel after it already contains "apple", the operation fails with a BoundsError. To avoid this error, ensure that the channel has sufficient capacity or use non-blocking operations like put! with a timeout or put!! instead.
See Also
Channel, close, put!, take!,User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.