Skip to content

Instantly share code, notes, and snippets.

@yowchun93
Created July 28, 2020 03:41
Show Gist options
  • Save yowchun93/a52cf71f8bc268de5c386540f19a4c2d to your computer and use it in GitHub Desktop.
Save yowchun93/a52cf71f8bc268de5c386540f19a4c2d to your computer and use it in GitHub Desktop.
Simulation race conditions using Threads
it 'does not allow multiple reservations on same spot' do
wait_for_all_threads = true
reservation_counter = ReservationCounterQuery.find_or_initialize_by_params(account, {
schedule_id: schedule.id,
date: Date.today.to_s
})
form1 = Reservation::SpotBooking::CreateForm.new(count: 1, reserved_spots: '1')
form2 = Reservation::SpotBooking::CreateForm.new(count: 1, reserved_spots: '1')
attributes = [
{
form: form1,
credit: credit,
user: user
},
{
form: form2,
credit: credit2,
user: user2
}
]
threads = attributes.map do |attrs|
Thread.new do
true while wait_for_all_threads
Reservation::Operations::SpotBooking::CreateSpotBooking.call(
form: attrs[:form],
deducted_credit: attrs[:credit],
reservation_counter: reservation_counter,
user: attrs[:user]
)
end
end
wait_for_all_threads = false
threads.each(&:join)
expect(reservation_counter.reservations.count).to eq(1)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment