how to use lock in Julia

2019-05-02 10:54发布

问题:

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