Semaphores in libc
Petr Baudis
pasky@suse.cz
Thu Dec 31 13:55:00 GMT 2009
On Thu, Dec 31, 2009 at 01:26:09PM +0000, Paulo J. Matos wrote:
> On Thu, Dec 31, 2009 at 1:22 PM, Petr Baudis <pasky@suse.cz> wrote:
> > On Thu, Dec 31, 2009 at 01:14:42PM +0000, Paulo J. Matos wrote:
> >> Â fl.l_len = 0;
> >
> > I'm not really that familiar with file region blocks, but I'd expect
> > this to be a problem - try non-zero len; but if you end up doing this,
> > I think semaphores are more elegant. flock() locks (albeit less portable)
> > might be a better fit.
> >
> > Ultimately, the best practice is to lock directly the resource you need
> > exclusive access to - what are you doing in the critical section?
> >
>
> In the critical section I am creating a directory. The directory has
> the name 'runx' where x is an integer > 0.
>
> The critical section tries to find the first x such that runx does not
> exist and when it does not exist, it creates it.
> Now, the current problem without the lock is that once I get 24
> processes in, two of the processes find that run2 does not exist, and
> both use it as their directory.
But what's the problem? Why not simply
int i = 0;
char buf[PATH_MAX];
do {
snprintf(buf, sizeof(buf), "run%d", ++i);
} while (mkdir(buf, 0777) < 0 && errno == EEXIST);
mkdir() should be atomic, so each process will always pick a different
name.
--
Petr "Pasky" Baudis
A lot of people have my books on their bookshelves.
That's the problem, they need to read them. -- Don Knuth
More information about the Libc-help
mailing list