开发者

Best way to Unit Test if Some Code is Thread Safe? [duplicate]

This question 开发者_运维百科already has answers here: Closed 11 years ago.

Possible Duplicate:

Unit test for thread safe-ness?

I'm looking for best way to unit test if some code is thread safe.

I'm using NUnit and Moq as unit test framework.


Well, does your code use concurrency? Because if it doesn't it already thread-safe. I believe your question is fundamentally wrong and should have been something along the line of "How do I design thread safe code?"

The problem with such a question is that it's very broad and there are a plethora of things to consider when designing code to be thread-safe.

However, something you can do to test your code, is to use brute force and multiple threads over an extended period of time. If the results are inconsistent, then there could be a synchronization problem. The issue here is of course that the inconsistent results doesn't have to be a concurrency related issue, it could still have happen using a single thread.

What you need to do is to look at the code that you expect to be thread-safe and basically ask yourself "What happens if I sleep for an indefinite amount of time here?". If you conclude that everything works while running the concurrent code with a lot of random sleep durations interleaved (this makes concurrency issues more apparent) then you're on the right track.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜