What's the best practice to manage global state in thread-safe way in Swift NIO based web apps like Vapor, Kitura?
I want to store a simple integer value in memory and pass to clients.
I chose the simplest way like having a mutable variable with a struct type and two closures, a setter (POST /value) and a getter (GET /value) that manipulates it. I suppose race condition can easily occur without additional protection around the variable.
One way is to use GDC queues or I can rely on pthread facilities.
I appreciate your suggestions,
There are many good options, but the best choices depend on exactly your trade offs and environments.
The most simply thing to do is to use a class and a lock. Many developers are excessively afraid of locks, but when you have nothing more specific in mind locks are a sensible idea. You can have a class that stores the property in question, and allows you to access it via a lock.
GCD serial queues also work well, where queue.sync is an effective replacement for a lock.
There are other solutions for more complex cases where you can use message passing to avoid sharing the global state, but for simple cases the above two options are just fine.