简体   繁体   English

Python中命名的信号量?

[英]Named semaphores in Python?

I have a script in python which uses a resource which can not be used by more than a certain amount of concurrent scripts running. 我在python中有一个脚本,它使用的资源不能超过一定数量的并发脚本运行。

Classically, this would be solved by a named semaphores but I can not find those in the documentation of the multiprocessing module or threading . 传统上,这可以通过命名的信号量来解决,但我无法在多处理模块或线程的文档中找到它们。

Am I missing something or are named semaphores not implemented / exposed by Python? 我是否遗漏了某些东西,或者是未被Python实现/暴露的命名信号量? and more importantly, if the answer is no, what is the best way to emulate one? 更重要的是,如果答案是否定的,那么模仿一个人的最佳方式是什么?

Thanks, Boaz 谢谢,波阿斯

PS. PS。 For reasons which are not so relevant to this question, I can not aggregate the task to a continuously running process/daemon or work with spawned processes - both of which, it seems, would have worked with the python API. 由于与此问题不太相关的原因,我无法将任务聚合到持续运行的进程/守护进程或使用生成的进程 - 这两者似乎都适用于python API。

I suggest a third party extension like these , ideally the posix_ipc one -- see in particular the sempahore section in the docs. 我建议像这样的第三方扩展,理想情况下是posix_ipc扩展 - 特别是参见文档中的sempahore部分。

These modules are mostly about exposing the "system V IPC" (including semaphores) in a unixy way, but at least one of them ( posix_ipc specifically) is claimed to work with Cygwin on Windows (I haven't verified that claim). 这些模块主要是以一种单一的方式暴露“系统V IPC”(包括信号量),但至少其中一个(具体是posix_ipc )声称可以在Windows上与Cygwin一起工作(我还没有证实这个说法)。 There are some documented limitations on FreeBSD 7.2 and Mac OSX 10.5, so take care if those platforms are important to you. FreeBSD 7.2和Mac OSX 10.5有一些记录的限制 ,所以请注意这些平台对您来说很重要。

You can emulate them by using the filesystem instead of a kernel path (named semaphores are implemented this way on some platforms anyhow). 您可以使用文件系统而不是内核路径来模拟它们(命名信号量无论如何都会在某些平台上以这种方式实现)。 You'll have to implement sem_[open|wait|post|unlink] yourself, but it ought to be relatively trivial to do so. 你必须自己实现sem_[open|wait|post|unlink] ,但这样做应该是相对微不足道的。 Your synchronization overhead might be significant (depending on how often you have to fiddle with the semaphore in your app), so you might want to initialize a ramdisk when you launch your process in which to store named semaphores. 您的同步开销可能很大(取决于您在应用程序中调整信号量的频率),因此您可能希望在启动存储命名信号量的进程时初始化ramdisk。

Alternatively if you're not comfortable rolling your own, you could probably wrap boost::interprocess::named_semaphore ( docs here ) in a simple extension module. 或者,如果您boost::interprocess::named_semaphore滚动自己,可以将boost::interprocess::named_semaphore此处为docs )包装在一个简单的扩展模块中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM