开发者

Any way to limit program to one CPU without caring which one?

I have a program which is occasionally malfunctioning a开发者_StackOverflownd I'm wondering whether the problems might be related to different threads running on different cores handling reads and writes in a different order (I know the x86 memory model requires different cores to do things mostly as expected, but there are some cases where reads and writes couldn't be resequenced on a single CPU but might on a multi-core system). Setting processor affinity to some specifically-selected arbitrary CPU core doesn't seem like a good idea (if that core happens to be busy, there's no reason all threads shouldn't be able to migrate to some other core, provided there's a full cache flush first). Is there any way to simply direct that all threads must run on the same core, but I don't care which one it is?

PS--My understanding is that if one thread writes some data to a class instance and then does a CompareExchange on a class reference (so the reference will point to the newly-modified instance), that implies that all changes to the instance will be written out to memory before the class reference; code running on another thread on the same CPU which uses that class reference will either use the old value of the class reference or will see the changes that were made to the instance; code running on other CPU's, however, could in some tricky circumstances see the new value of the class reference but not see the new data that was written to the instance. Is my understanding in error?


No, and this won't fix your problem either. Even on a single core, the OS can reschedule your program at any time, causing the same problems. You might be able to make the problem less likely to happen - but that just means the problem, when it inevitably appears in the field, will be that much harder to debug. Fix your lack of locking now, before it comes to bite you later.

To be more specific, there is no Windows (or Linux) function that tells the OS, "Keep all my threads on the same core". You can tell the OS to keep them all on some specific core, but you can't leave it floating like that. Since memory barriers are relatively cheap, it's best simply to implement them the right way. Even locked operations are relatively cheap on modern processors - the CPU simply obtains a lock on the cache line when it begins the read part of the operation (which it has to have on any write anyway) and refuses to release the lock until the locked operation is complete.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜