Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use lock in Julia

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?

like image 969
Yves Avatar asked Nov 18 '15 11:11

Yves


People also ask

How do you set number of threads in Julia?

The number of threads can either be specified as an integer ( --threads=4 ) or as auto ( --threads=auto ), where auto sets the number of threads to the number of local CPU threads. The -t / --threads command line argument requires at least Julia 1.5. In older versions you must use the environment variable instead.

Does Julia support multithreading?

The Julia language implements multithreading using task parallelism where tasks communicate in shared memory as described in their article Announcing composable multi-threaded parallelism in Julia. In task parallelism, a task refers to a computational task such as executing a function.

Is Julia single threaded?

Julia's multi-threading provides the ability to schedule Tasks simultaneously on more than one thread or CPU core, sharing memory. This is usually the easiest way to get parallelism on one's PC or on a single large multi-core server. Julia's multi-threading is composable.


2 Answers

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
like image 147
Yves Avatar answered Sep 21 '22 23:09

Yves


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
like image 34
HarmonicaMuse Avatar answered Sep 23 '22 23:09

HarmonicaMuse