Hi, I’m going to add some member variables in controller. Looks like each request handler in controller is running in req.eventloop, which means the controller is cross-thread. But I heard in Vapor 4 controller is thread-safe. Is that true? How it works?
It depends is the answer. IIRC if you use
structs you’ll get a copy of the copy on each thread, but classes will share a copy. However, that doesn’t matter, it matters what you pass in. Whatever you pass in needs to be threadsafe. The style of Vapor 4 (of using request/application extensions) encourage good practise, so that you get an instance of the service you want specific to the request’s event loop (and therefore thread). What are you trying to do? Because if you want a thread safe controller, that might be a code smell
There is an access token shared globally which need update every 2 hours. When a request comes in, it will check the token and update the token if necessary in the request’s event loop. A lock is required to protect the token read/write. But I heard vapor 4 controller member variable is thread-safe, I think maybe token as a controller member variable is a good idea to make it lock-free.
Have a look at how Vapor uses
Lock to keep configuration of services thread safe, that’s probably the best way to do it