
Untitled
By: a guest on
Apr 25th, 2012 | syntax:
None | size: 0.93 KB | hits: 9 | expires: Never
Determining Thread Safety in Unit Tests
public class MyClass
{
private List<string> MyList = new List<string>();
public void Add(string Data)
{
MyList.Add(Data); //This is not thread safe!!
}
}
boolean failed = false;
int iterations = 100;
// threads interact with some object - either
Thread thread1 = new Thread(new ThreadStart(delegate() {
for (int i=0; i<iterations; i++) {
doSomething(); // call unsafe code
// check that object is not out of synch due to other thread
if (bad()) {
failed = true;
}
}
});
Thread thread2 = new Thread(new ThreadStart(delegate() {
for (int i=0; i<iterations; i++) {
doSomething(); // call unsafe code
// check that object is not out of synch due to other thread
if (bad()) {
failed = true;
}
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
Assert.IsFalse(failed, "code was thread safe");