开发者

Writing atomic function

开发者 https://www.devze.com 2023-01-06 22:17 出处:网络
I want to implement an 开发者_JAVA技巧atomic function in C language, so that the process or thread will not be preempted while executing the function.If you\'re in the kernel and you really need to di

I want to implement an 开发者_JAVA技巧atomic function in C language, so that the process or thread will not be preempted while executing the function.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消