How to write an automated test for thread safety

后端 未结 6 722
醉话见心
醉话见心 2020-12-31 18:29

I have a class which is not thread safe:

class Foo { 
    /* Abstract base class, code which is not thread safe */ 
};

Moreover, if you hav

6条回答
  •  灰色年华
    2020-12-31 18:58

    Instead of just checking that a particular thread is finished or not, why not create a fake Foo to be invoked by your wrapper in which the functions record the time at which they were actually started/completed. Then your yield thread need only wait long enough to be able to distinguish the difference between the recorded times. In your test you can assert that another_func's start time is after some_func's start time and it's completed time is before some_funcs completed time. Since your fake class is only recording the times, this should be sufficient to guarantee that the wrapper class is working properly.

    EDIT: You know, of course, that what your Foo object does could be an anti-pattern, namely Sequential Coupling. Depending what it does, you may be able to handle it by simply having the second method do nothing if the first method has not yet been called. Using the example from the Sequential Coupling link, this would be similar to having the car do nothing when the accelerator pedal is pressed, if the car has not yet been started. If doing nothing is not appropriate, you could either wait and try again later, initiate the "start sequence" in the current thread, or handle it as an error. All of these things could be enforced by your wrapper as well and would probably be easier to test.

    You also may need to be careful to make sure that the same method doesn't get invoked twice in sequence if an intervening call to another method is required.

提交回复
热议问题