[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Threads
Pierre Phaneuf wrote:
> > BTW - What exactly is a semaphore? I've heard of them before, and I gather
> > that they're similar to threads, but I know even less about them
>
> This is not a threading mechanism, but a communication one. SysV IPC has
> a semaphore system in it, but you can implement one yourself rather
> easily. It is simply something like an integer (or maybe a bool, I don't
> remember much) variable that is shared between the processes or threads.
> The idea is that one process can raise the semaphore (by doing an atomic
> increment for example) and the other watch for the semaphore being
> raised. For example, when you have one working thread and a main thread,
> the working thread might raise a semaphore to tell the main thread it
> has finished its work.
Actually, not only the "raise" and "lower" operations needs to be atomic
- you also need to ensure that the flag does not change while you
perform operations that depends on the state of the flag.
eg;
int flag = 0;
...
// One thread
while (flag != 0) { sleep (1); }
// I can use it
flag = 1; // Make sure no one else can use it
// Do something
flag = 0;
...
The above will fail miserably. One needs to be able to -lock- the
semaphor;
semaphor flag = init_whatever;
...
lock(flag); // Make sure we are the only ones getting access to the
flag.
// Do some work;
unlock(flag);
Most often some sort of OS support is needed.
Mads