单元测试并发代码

单元测试并发代码

问题描述:

我的周末项目包括编写跨平台并发原语库(关键部分,读/写互斥体,互锁整数,事件等),并且想知道如何单元测试这些东西。我意识到,测试并发代码本身很困难,但是测试代码的原语不是那么难,是吗?

My weekend project consists of writing a cross-platform concurrency primitives library (critical sections, read/write mutexes, interlocked integers, events, etc) and was wondering how to unit test this stuff. I realize that testing concurrent code is hard in itself, but testing the primitives of said code couldn't be that hard, could it?

结果是, 。至少对我来说是这样。

Turns out, it is that hard. At least, for me it is.

那么你怎么去处理呢?例如,我甚至不知道从哪里开始测试关键部分。

So how would you go about approaching this? Just as an example, I don't even know where to start with testing critical sections.

不要考虑单位测试,想想要指定的行为。例如:

Don't think about unit tests, think about the behaviour you want to specify. For example:

Given_an_unlocked_lock
    It_should_be_possible_to_take_it
Given_a_locked_locked
    It_should_not_be_possible_to_take_it_from_another_thread
    It_should_be_possible_take_it_from_the_same_thread
Given_a_locked_locked_when_unlocked
    It_should_be_possible_to_take_it
Given_a_locked_locked_when_owning_thread_terminates
    It_should_be_possible_to_take_it

将帮助你识别做什么。是的,可能你需要一个帮助线程在你的单元测试,以使它发生。也许这个例子是有帮助的。

I think that will help you identify what to do. And yes probably you need a helper thread in your unit tests to make it happen. Maybe this example is helpful.