In Perl 5, how to queue a process/application after it reaches a maximum limit

大兔子大兔子 提交于 2019-12-06 15:32:20

You have a few general approaches:

Quick and Dirty

Have a directory with N lockfiles, and have each process try to lock each file in turn, sleeping a bit.

Caveat: It's a busy loop, yes, but it might be good enough.

Daemonic Redesign

Turn foo.pl into a local socket-listening daemon, as it is easy for a parent process to manage concurrency of its children. Turn your cron jobs into blocking requests for the daemon to so something. (See, e.g., Parallel::ForkManager).

Caveat: You'll have to carefully re-implement setuid/privilege changing code if you were using cron to run foo.pl as multiple different users.

Interprocess Semaphores, SysV

IPC::Semaphore is a somewhat more convenient interface to the SysV semget family of functions in perlfunc, and the SEM_UNDO flag means that the unexpected process death of one of your workers won't "waste" a semaphore increment.

Caveat: You'll likely need to create and initialize the SysV semaphore in a separate process, distinct from foo.pl, since you cannot create and initialize a SysV semaphore in an atomic operation.

Interprocess Semaphores, POSIXly

POSIX::RT::Semaphore also supports interprocess semaphores. The API is simpler than SysV, and semaphores can be exclusively created and initialized to a value in an atomic syscall.

This is probably what I'd use.

Please see comment from @tsee in @pilcrow answer above. Steffen Muller's IPC::ConcurrencyLimit can control the number of concurrenct processes on cooperative multi processing nicely.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!