Re: Porable Semaphore implemented in C++ ?
On Oct 1, 12:32 pm, Steven Woody <narkewo...@gmail.com> wrote:
On Oct 1, 5:08 pm, Zeppe <ze...@remove.all.this.long.comment.yahoo.it>
wrote:
Steven Woody wrote:
i am writting some classes, those need to work in both linux and
windows. in my problem, there are mutiple productor and one
consumer, productors each in a different thread are trying to append a
byte to a shared buffer while the consumer in the main thread will
remove one byte every some milliseconds.
the productors has to wait if the buffer is read/write by other
productors or the consumer, on the other hand, the consumer should
immediately exit if the buffer is read/write by any productor.
i am thinking, for the problem above, the semaphore can help. is
there a portable semaphore implementation in C++ ( if not, in C )?
A good idea in my opinion would be to look for the boost
thread library. It's not standard, but it's portable
enough. It hasn't got semaphores, though. However, I think a
mutex solution can be devised easily and it may be less
error-prone.
ok, i go to study it. but i have one thing in doubt:
semaphores or other mutex solutions should have to dependent
on some sort of 'atomic operation' which should be
OS-dependent, am i right? so how can a library implement it
without depends on OS?
The library implementation isn't necessarily "portable"; they
have a separate implementation for Windows and for Posix threads
(and don't support anything else, as far as I know). The whole
point being that by using such a library, that becomes their
problem, not yours. (How you open and write to a file also
depends on the system. But if you use std::ofstream, that's
someone else's problem, too.)
ps. how to implement atomic operation in Linux and how to
implement it in Windows? thanks.
In both cases, you have Mutex (called CriticalSection under
Windows, I think). That's not always sufficient, of course, so
boost::threads also provide conditions, modeled on Posix
conditions; I don't know how they implement this under Windows,
but they do (and so I don't have to).
Lockfree algorithms also exist for your specific problem, I
think, but they require special machine instructions to ensure
that the modifications in one thread are visible in the same
order in other threads. Which means that you cannot implement
them in standard C++.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34