user316117
user316117

Reputation: 8271

Thread-safety of this design?

I've inherited some C# code to maintain and I have some reservations about the design, but I don't know if I should. This is for a C# application that controls some industrial processes.

We have a method DoCertify() which fires off a worker thread to control a sequence of industrial processes. In each step of the sequence it controls some machinery then compiles some data.

The caller, in the UI thread, allocates an array of objects representing these steps and calls DoCertify() passing the array as a ref variable. Periodically as each step in the sequence is done, DoCertify()'s worker thread fills in the data in the associated element of the array (step 0, element0, step 1, element 1, etc), and invokes a delegate (i.e., a callback to the UI thread) announcing that step is done, and then it continues to the next step.

When the callback in the UI thread is called, it reads and displays the data in the just-finished element of the array. In this manner, as DoCertify() runs its progress can be updated on the display.

There's no explicit thread-safety built into this but the code's writer says that it's inherently safe because once the worker thread writes to an element and signals that it's done, it will never write to that element again, so there's no danger of the worker thread and UI thread trying to access the same element in the array at the same time.

Does that provide sufficient thread safety or should more explicit thread-safety be build in to this design?

Upvotes: 0

Views: 42

Answers (1)

Kit
Kit

Reputation: 21699

It's thread-safe, but not safe-safe. By that I mean if what you say is true that the caller doesn't read anything until the callee calls the callback, and the caller doesn't modify the original data after handoff to the the worker, etc -- you're fine.

But it's not safe-safe because a developer might easily do something in the future like try to reuse the array between calls, add a value to the array, change one, or otherwise take advantage of the ref thinking they can use the values in the same scope. Who knows.

The design you describe can't prevent misbehavior on either end. A design that works on a copy of the array (and copies of the array elements) is a better bet.

Upvotes: 1

Related Questions