# 【lock】满了的Channel锁不住 ！！！

``````function showme(n)
c = Channel(0)
t1 = @async begin
sleep(3)
for _ in 1:n
put!(c, 0)
sleep(0.1)
end
end
t2 = @async begin
# sleep(rand())
lock(c)
for _ in 1:n
put!(c, 1)
sleep(0.1)
end
unlock(c)
end
d= []
sleep(3)
for _ in 1:2n
push!(d, take!(c))
end
show(d)
end
``````
``````julia> showme(5)
Any[0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
# 本以为应该是下面这个：
#Any[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
``````

``````    c = Channel(2n)
``````

``````julia> showme(5)
Any[1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
julia> showme(5)
Any[1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
julia> showme(5)
Any[1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
``````

``````    c = Channel(n>=1 ? n-1 : 0)
``````

``````julia> showme(5)
Any[1, 1, 1, 1, 1, 0, 0, 0, 0, 0] (第一次运行)
julia> showme(5)
Any[1, 1, 1, 1, 0, 1, 0, 0, 0, 0]
julia> showme(5)
Any[1, 1, 1, 1, 0, 1, 0, 0, 0, 0]
``````

``````   c = Channel(n)
``````

``````julia> showme(5)
Any[1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
julia> showme(5)
Any[1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
julia> showme(5)
Any[1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
``````

https://discourse.julialang.org/t/why-lock-does-not-work-for-full-channel/65710/5

1 个赞