I want to implement an atomic function in C language, so that the process or thread will not be preempted while executing the function.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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()andpreempt_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.