Skip to content

Instantly share code, notes, and snippets.

@ahogen
Last active August 2, 2017 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahogen/35288b276134fe24c9a7486f959d4c18 to your computer and use it in GitHub Desktop.
Save ahogen/35288b276134fe24c9a7486f959d4c18 to your computer and use it in GitHub Desktop.
A [Julia](https://julialang.org/) script, demonstrating the use of a semaphore to protect asyncronous data accesses.
###############################################################################
# File: julia_async_tasks_semaphore_demo.jl
# Author: Alex Hogen (@ahogen on Github)
#
# This is a demo script I made for myself just to see how Julia's
# syntax for semaphores looks. This script is a basic demonstration
# of a producer and consumer task using a semaphore to protect the
# code sections where the global data variable is accessed.
#
# I built and ran this script with Julia 0.6.0.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
# OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
###############################################################################
# Global semaphore
sem_state = Base.Semaphore(1)
# Global variable
num = 0
# A Producer task
function task1()
Base.acquire(sem_state)
println("T1 lock")
println(num)
global num = 12345
sleep(0.3)
Base.release(sem_state)
println("T1 unlock")
end
# A Consumer task
function task2()
Base.acquire(sem_state)
println("T2 lock")
println(num)
Base.release(sem_state)
println("T2 unlock")
end
println("Start")
# Start first task asynchronously
t1 = @async task1()
# Wait for a short time
sleep(0.1)
# Start second task asynchronously
t2 = @async task2()
# Wait for both tasks to exit before exiting this script as a whole
wait(t1)
wait(t2)
println("End")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment