c# - How to unit test a thread safe queue -


i need simple data structure these requirements:

  • it should behave queue,
  • all enqueue operations should atomic.

i have limited experience multithreading, came to:

public class tickets {     private concurrentqueue<uint> _tickets;      public tickets(uint from, uint to)     {         initialize(from, to);     }      private readonly object _lock = new object();     public void initialize(uint from, uint to)     {         lock(_lock)         {             _tickets = new concurrentqueue<uint>();              (uint = from; <= to; i++)             {                 _tickets.enqueue(i);             }         }     }      public uint dequeue()     {         uint number;         if (_tickets.trydequeue(out number))         {             return number;         }          throw new argumentexception("ticket queue empty!");     } } 

first question: code ok?

secod question: how can unit test class (for instance 2 threads perfoming dequeue operation periodically on queue elements (1, 2, 3, 4, 5, 6) , first thread should odd numbers , second thread numbers)? tried this, asserts aren't executing:

[test] public void test() {     var tickets = new tickets(1, 4);     var t1 = new thread(() =>                             {                                 assert.areequal(1, tickets.dequeue());                                 thread.sleep(100);                                 assert.areequal(3, tickets.dequeue());                             });       var t2 = new thread(() =>                             {                                 assert.areequal(2, tickets.dequeue());                                 thread.sleep(100);                                 assert.areequal(4, tickets.dequeue());                             });      t1.start();     t2.start(); } 

the problem multithreading , unit tests 1 of timing. when try introduce multiple threads unit tests run risk of non-reproducable test results, tests pass not other times.

but explain why asserts may not executing, unit test completes before threads. needs wait threads complete rather kicking them off , moving on. it's feasible unit test framework not threadsafe or capable of asserts being called other threads.

sorry it's not solution, don't know of automated testing solution multithreaded code either.

see also: how should unit test threaded code?


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -