Suppose we have a file copy program. It has two threads, a UI thread displaying the progress of the copy operation and a work thread copying the file.
The UI has a button for canceling the process. Which pattern are you suggest here for transfering cancel event to copy thread?
I want an object-oriented solution.
If you’re using Java, use Thread.interrupt – this is exactly the scenario that system was designed for.
Otherwise, you’ll need to look at what synchronisation primitives your language provides. If it has an Event synchronisation class, use that (periodically poll the event in the worker thread and terminate if it is fired, signal the event if the user clicks the button). Events are sometimes called Condition, so check for that name too.
If not, you’ll have to implement one yourself, using whatever memory barrier primitive your language provides. All you need is a class with a boolean variable initialised to false and two methods: set, which sets the variable to true and executes a write barrier, and get, which executes a read barrier and returns the variable. In most languages, if you don’t have explicit memory barrier operations, then you can use whatever mutual exclusion operation is provided instead.
The Command
pattern comes to my mind. You have a Command
interface/trait/abstract class and create for example a StopCopyingCommand
and send it to the copy thread.
The copy thread btw. could be implemented using the State
pattern so that it accepts different kinds of commands for different states.
5