5

I have a simple chunk of deterministic work that only takes thirteen machine instructions to complete. Because the first instruction takes a homemade semaphore (spinlock) and the last instruction releases it, I am safe from all of the other threads running on the other cores as they are attempting to take and give the same semaphore.

The problem arises when some thread interrupts a thread holding the semaphore before it can finish its "critical section". Worst case the interruption kills the thread while holding the semaphore or as can happen one of the threads normally competing for the semaphore branches out into code that can generate the interrupt causing a deadlock.

I don't have a way synchronizing with these other threads when they branch into those parts of the code I can't control. I think I need to disable interrupts like I used to do in my old VxWorks days when I was running in kernel mode. Its always thirteen instructions and I am always completely safe if I can get all thirteen instructions done before I have to honor an interrupt. Oh and it is all my own internal data, other that the homemade semaphore there is nothing that locks anything else up.

I have read several answers that I think are close. Most have to do with Critical Section calls on the Windows API (wrong OS but maybe the right concept). Most of the wrong solutions assume that I can get all of the offending threads to use a mutex that I create with the pthread libraries.

I need this solution in C/C++ on Linux and Solaris.

Johnny Crash's question is very close prevent linux thread from being interrupted by scheduler

KermitG also Can I prevent a Linux user space pthread yielding in critical code?

Thanks for your consideration.

4

1 回答 1

5

您可能无法阻止用户模式线程的抢占。关键部分(和所有其他同步对象)可以防止线程冲突,但是它们绝不会阻止它们被操作系统抢占。

如果你的其他线程在超时时分支到某个东西,而那个东西可能会导致死锁——你有一个设计问题。

一个正确的设计应该是最悲观的:抢占可能无处不在,时间不确定。

于 2012-04-09T21:18:55.157 回答