I have programed for my application to make a call to an external rest service when a user makes a request. This allows me to get the data to serve there request. The service has requested that I limit the concurrent connections. How would I setup something like a resource pool in PHP to limit the concurrent calls?
Share
And here goes one of the most annoying “features” of PHP – no application scope. Scripts are executed over and over again for each request without any chance of further management.
But to stop complaining and start being helpful: Use UNIX file locks. If you are limited to 5 concurrent connections to the external resource, create 5 empty files. Whenever you want to use them, try to acquire an exclusive lock on one of them (flock() function). If you can’t, the current “script instance/thread” has to wait until the lock is released.
This is not really nice, but it’s perfectly thread-safe as flock is atomic. I have my own wrapper for handling these “critical sections” which require so called thread lockout. The obvious downside of this approach is performance overhead and inability to launch multiple app servers without shared FS (then we do it either by shared FS or shared memchache space).