1

I want to use multi-thread Puma as a production server so my code should be thread-safe. I read that the usage of global variables isn't thread-safe. What is the alternative to global variables in this case? I used global variables (without value changes) as Redis keys for set/get etc.

#initializers/redis.rb

$DRIVER_LOCATIONS = "driver_locations"

and in code

REDIS.with do |conn|
  conn.geoadd($DRIVER_LOCATIONS, latitude, longitude, id)
end

Or there is no need to change something?

ViT-Vetal-
  • 2,431
  • 3
  • 19
  • 35
  • 1
    If you're only reading them, then you should be fine. Most/all problems arise when you try to concurrently write to the same place. BTW, why a global var here, and not a constant? – Sergio Tulentsev Jan 19 '19 at 19:31
  • @anothermh: oh, but you cause total chaos in your app with a single-threaded database. Without a database at all, even. – Sergio Tulentsev Jan 19 '19 at 20:46
  • @anothermh: I was saying that the single-threaded nature of redis has nothing to do with the amount of corruption/damage that an improperly implemented multi-threaded app can do to itself. – Sergio Tulentsev Jan 19 '19 at 21:36

1 Answers1

0

As stated in the comments, you should probably use a constant there instead of a global variable

#initializers/redis.rb

DRIVER_LOCATIONS = "driver_locations"

# ...

REDIS.with do |conn|
  conn.geoadd(DRIVER_LOCATIONS, latitude, longitude, id)
end

Using the global variable shouldn't be that bad in your use case as it's set during initialization and I'm assuming that it's only done once.

  • fyi, constants can be changed see https://stackoverflow.com/questions/26537564/ruby-constants-seem-to-be-invisibly-alterable – lacostenycoder Feb 12 '19 at 19:18