How to achieve atomic increment/decrement in Linux
Hi,
I am new to Linux programming. Is there anyway in Linux that can achieve atomic increment/decrement for an integer variable without being interrupted? It means that the thread should not give chance for other thread to run until the increment/decrement is completed. Please help. Many thanks. Regards. |
Try
Linux semaphore thread in your favorite WEB search engine. |
Quote:
Kevin Barry |
Quote:
|
if you are threading you should be using mutexes.
and conditions etc. |
Quote:
|
If you must have atomic operations rather than using mutexes (Knuth says that "premature optimization is the root of all evil"!), then have a look at how the kernel atomic operations are implemented in C. They are of course processor dependent, not portable.
As far as I know, the Posix API provides no way of doing atomic operations (apart from the normal semaphores etc). |
Quote:
Kevin Barry |
The question is badly formulated (or it is a bad question).
Code:
i--; Code:
decr [bp-16] An atomic operation usually consists of more than one operations which might not be interrupted. Like: Code:
if (i > 0){ In the example I gave above the more than one instructions, if the must be atomic, must be protected in some way. But from what? So before any answer can given about how to achieve atomicness (sp?) we would like to know which instructions should be prevented against what. jlinkels |
Quote:
It is also poor practice to rely on the compiler to produce the same code in every context. There are ways of mitigating this (such as making use of 'volatile'), but it is best to keep such sensitive code inside a library of thread-aware functions, rather than sprinkled through user code. |
Quote:
I.e. I was talking about classical critical section protected by semaphore. ... By the way, the first match in 'Yahoo' gives a link to a Qt function which implements safe increment - and that was the main point of my post. |
I think the question is a bit ambiguous, the OP ask for an atomic increment/decrement while most likely he wants to protect this operation from interruption.
Mutexes or semaphores are the way to go. IIRC these functions are part of the threads library in C. It should not be forgotten that the other thread should use the same mutexes to protect the same variable in the other thread. Thinking about how a semaphore is decremented in a thread safe-way is a challenge in its own. jlinkels |
All times are GMT -5. The time now is 11:02 AM. |