【发布时间】:2010-11-05 17:58:28
【问题描述】:
我有一个在 mod_perl 下执行的 Perl CGI 程序。在程序中,我想防止多个进程同时访问一个资源。
# Semaphore Initialization Code
# 10023 is unique id, and this id will be same across different apache process.
# 1, Only one semaphore being created.
# 0722, as all process will be execute under apache account. Hence, they will all having '7' privilege.
my $sem = new IPC::Semaphore(10023, 1, 0722 | IPC_CREAT); # Code(1)
# Set 0th (one and only one) semaphore's value to 1, As I want to use this semaphore as mutex.
$sem->setval(0, 1); # Code(2)
问题是:
- 如果之前从未创建过 10023 id 的信号量(无论是由同一进程还是其他进程),我如何才能让 Code(1) 创建一个新的信号量?
- 如何仅在第一次创建具有 10023 id 的信号量时执行 Code(2)?信号量只能初始化一次。
另一种方法是创建一个空文件用于锁定目的。但是,这最终将拥有数千个临时文件。 link text
【问题讨论】:
-
为什么会有数千个临时文件?如果您打算使用一个信号量,则只需使用一个文件。
-
我将使用每个客户基本的信号量。因为一个客户可以一次发送多个 HTTP 请求。