c# - Threading test question -



c# - Threading test question -

i had interview question in test similar below, not have much experience of development using threads can please help advise me how approach question?:

public class stringqueue { private object _lockobject = new object(); private list<string> _items = new list<string>(); public bool isempty() { lock (_lockobject) homecoming _items.count == 0; } public void enqueue(string item) { lock (_lockobject) _items.add(item); } public string dequeue() { lock (_lockobject) { string result = _items[0]; _items.removeat(0); homecoming result; } } }

is next method thread safe above implementation , why?

public string dequeueornull() { if (isempty()) homecoming null; homecoming dequeue(); }

it seems me reply no.

while isempty() procedure locks object, released phone call returned - different thread potentially phone call dequeueornull() between phone call isempty() , dequeue() (at time object unlocked), removing item existed, making dequeue() invalid @ time.

a plausible prepare set lock on both statements in dequeueornull(), no other thread phone call dequeue() after check before dequeue().

c# multithreading

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

c# - Can ProtoBuf-Net deserialize to a flat class? -

javascript - Change element in each JQuery tab to dynamically generated colors -