how to use lock in Julia

自闭症网瘾萝莉.ら 提交于 2019-12-12 09:39:14

问题


I'm working with Julia. The IDE is Juno.

If I'm right, @async can generate a task, it's just like a thread.
So we can do this:

@async begin
   # do something1
end
@async begin
   # do something2
end

Now, I need to lock a thread. For example, do something1 is to push message to a list and do something2 is to pop message from the same list.

It's like synchronized in Java.

what is synchronized in julia?


回答1:


There is also a @sync macro:

help?> @sync

Wait until all dynamically-enclosed uses of @async, @spawn, @spawnat and @parallel are complete. All exceptions thrown by enclosed async operations are collected and thrown as a CompositeException.

@sync @async begin
   # do something1
end

@sync begin
    # some code    
    @async begin
        # do something2
    end
    @async # do something 3
end



回答2:


To keep a block mutex:

mutex = RemoteRef()

@async begin
   put!(mutex, true)
   # do something1
   take!(mutex)
end
@async begin
   put!(mutex, true)
   # do something2
   take!(mutex)
end


来源:https://stackoverflow.com/questions/33778907/how-to-use-lock-in-julia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!