An Introduction to Multithreading

def get_sum_of_two_arrays(a1, a2)    sum_a1 = 0
a1.each {|e1| sum_a1 += e1}
sum_a2 = 0
a2.each {|e2| sum_a2 += e2}
return sum_a1 + sum_a2
end
def get_sum_of_two_arrays_with_threads(a1, a2)    # Does not need a return value immediately
Thread(get_sum_of_one_array(a1))
Thread(get_sum_of_one_array(a2)
# Now we need some way to combine the result of the two
return result of threads
end

The Thought Process

  • The game is being rendered
  • You are sending data to the server (your actions in-game)
  • You are receiving from the server (other people’s actions in-game)
Even if you lose your connection, you should still be able to fish
while true    render_game()
receive_data() # have to wait for this?
send_data()
end
while true    render_game()
if receive_data() # just wait & try to receive some data
=> then do something with the received data
end
send_data()
end
$game_data = {SOME_INITIAL_VALUE}tell some thread(wait_for_incoming_data)
then, using(incoming_data)
$game_data = incoming_data
end
end
while true
render_game($game_data)
send_data(whatever_the_player_is_doing)
end

Common problems

  • Security Issues: if a variable is accessible at a high level, this in turn makes it more vulnerable
  • Visibility Issues: a thread reads shared data before it is changed, but is unaware of an update to the data
  • Access Issue/Race Conditions: occur when multiple threads attempt to change a shared value at one time. This is one of the biggest concerns with multithreading, and its fixes provide their own issues, such as deadlocks and inefficient locking methods.

Ruby example

$delta = 5def pattern
i = 0
while true
puts i
i = i + $delta
sleep(3) # pauses program for 3 seconds
end
end
def change_delta
while true
i = gets.chomp.to_i
$delta = i
puts “Changed delta to: #{i}”
end
end
t1 = Thread.new{pattern()}
t2 = Thread.new{change_delta()}
t1.join()
t2.join()

Sources

--

--

--

NYC, fullstack

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Agave Development Update #14 / 04–10 July, 2021

Amazon Reinforcement Learning Simplifies Training and Deploying Robots

auto_technician.to_CODING

I Made a Login System. But It Can Work Without Back-End Engine

Creating a new django app and installing dependencies

SCSS in WordPress — Here’s How

Maximum profit by buying and selling shares by Dynamic Programming

Part 2 Version Controlling In Salesforce

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Elliott King

Elliott King

NYC, fullstack

More from Medium

Post Core, Road to Engineer: Week 0 (07/10/22)

Duck Typing Two (case study: bicycle tour)

Algorithms In Context #8: Shuffling

What is an MVC framework?