views:

154

answers:

2

Hi, I want to implement an atomic function in C language, so that the process or thread will not be preempted while executing the function.

+2  A: 

If you're in the kernel and you really need to disable preemption (probably not a great idea, I hope you know what you're doing) you can use preempt_disable() and preempt_enable() (see Documentation/preempt-locking.txt for details).

If you're outside the kernel, your options are very limited. What most multi-process or multi-threaded applications do is create mutexes that they use to self-limit themselves when accessing shared resources. (Think typical reader-writer locks.) But this is in no way atomic with respect to all the other processes on the system. It is simply atomic with respect to other processes following the same protocol.

(And given that even super-cheap laptops these days have multiple running CPU cores simultaneously, your goal of preventing other processes from running while your critical section is running is doomed to failure.)

You could grant your application the real-time scheduling priority, but this requires very careful programming, as lower-priority programs (such as X or ssh or bash or ..) wouldn't run unless you yield the processor or perform blocking IO. See sched_setscheduler(2) for details.

sarnold
How does the semaphore locking and releasing operations works?
Yogesh
@Yogesh, if you want to know how to use pthread semaphores, the manpages for `pthread_mutex_init(3)`, `pthread_mutex_lock(3)`, `pthread_mutex_unlock(3)` are where you should start. Perhaps `pthread_cond_signal(3)` if you want to use condition variables instead of bare mutexes, which may match your problem domain better. If you want to learn how to implement these primitives for yourself, I suggest reading Curt Schimmel's [Unix Systems for Modern Architectures: Symmetric Multiprocessing and Caching for Kernel Programmers](http://www.powells.com/biblio?isbn=9780201633382)
sarnold
+1  A: 

You're confusing two things:

  • "Atomic" means the operation either appears to have not run or to have completed entirely.
  • "Preemption" (loosely) means that other threads can run on your core without you yielding.

Even on a non-preemptive OS (e.g. classic Mac OS), things still aren't guaranteed to be atomic:

  • Interrupts can happen at any time (unless you disable interrupts too).
  • Code on other cores will run even if you disable interrupts.

It also helps to know why you think you need atomic operations. The easiest way to protect a shared data structure is to use a lock. If you're in the kernel, read Rusty Russell's Unreliable Guide to Locking (it might be a bit out of date). If you're in userspace, just use a pthread mutex.

tc.
thanks, i will use locking
Yogesh