Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

in Channel put!, convert value to Channel type #29092

Merged
merged 1 commit into from
Oct 20, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
in Channel put!, convert value to Channel type
`put!(ch::Channel{T}, v)` should convert `v` to type `T`.

This can prevent errors like:

```
julia> c = Channel{Int}(0)
Channel{Int64}(sz_max:0,sz_curr:0)

julia> @async put!(c, :a)
Task (runnable) @0x00007ff5b9d79270

julia> isready(c) && take!(c)
ERROR: TypeError: in take_unbuffered, in typeassert, expected Int64, got Symbol
Stacktrace:
 [1] take_unbuffered(::Channel{Int64}) at ./channels.jl:323
 [2] take!(::Channel{Int64}) at ./channels.jl:306
 [3] top-level scope at none:0
```
  • Loading branch information
tanmaykm committed Sep 11, 2018
commit 63e84da7c97839786ebed78bcea1b40d0a7fe006
3 changes: 2 additions & 1 deletion base/channels.jl
Original file line number Diff line number Diff line change
Expand Up @@ -246,8 +246,9 @@ Append an item `v` to the channel `c`. Blocks if the channel is full.
For unbuffered channels, blocks until a [`take!`](@ref) is performed by a different
task.
"""
function put!(c::Channel, v)
function put!(c::Channel{T}, v) where T
check_channel_state(c)
v = convert(T, v)
isbuffered(c) ? put_buffered(c,v) : put_unbuffered(c,v)
end

Expand Down
9 changes: 9 additions & 0 deletions test/channels.jl
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,15 @@ end
testcpt(32)
testcpt(Inf)
end

@testset "type conversion in put!" begin
c = Channel{Int64}(0)
@async put!(c, Int32(1))
wait(c)
@test isa(take!(c), Int64)
@test_throws MethodError put!(c, "")
end

@testset "multiple for loops waiting on the same channel" begin
# Test multiple "for" loops waiting on the same channel which
# is closed after adding a few elements.
Expand Down