October 08 2020

One of the challenges of writing multithreaded code is that it is often necessary to share data that was not designed to be used by multiple threads at the same time. In this blog post, I want to show two approaches to protect such data: duplication and wrap.

## Duplication

The first approach is the simplest. Just duplicate the data for each thread. For this to work, the data has to meet a few criteria:

• be easy to identify,
• have no hidden parts,
• be easy to duplicate,
• have no essential requirements to be shared at all times.

If the data meets all these criteria, then duplication is the fastest and safest option. Usually, data that can be used this way is essentially a group of values, like a pure structure in C++, containing unchanging simple values.

## Wrapping

If your data doesn’t meet the duplication criteria, the second approach of wrapping the data can be used. A common case is when you are given an interface that would need to be shared among multiple threads. Here are the steps to create multithread wrapping:

• Identify the interface that needs to be isolated.
• Write a thin multi-thread protector to the interface.
• Write a thin per-thread implementation of the interface.

To illustrate the technique, I will show you an example of a multi-thread wrapping I have recently done in C++. The code was part of the Tantrix Solver application I wrote. The particular item I needed to convert to multithreaded use was the progress report interface.

The code for that application is available on GitHub.

### Identify the Interface

The first step is to fully identify what will be used by the threads. This may require some refactoring if it is a disparate group of items. In the progress example, it was an interface called progress_t. Note that it only has one virtual function that really needs to be made thread-safe: update_progress().

   // Report progress of work.
//

struct progress_t
{
// Create a progress reporter.
progress_t() = default;

// Force to report the progress tally.
void flush_progress();

// Clear the progress.
void clear_progress();

// Update the progress with an additional count.
void progress(size_t a_done_count);

size_t total_count_so_far() const;

protected:
// Update the total progress so far to the actual implementation.
virtual void update_progress(size_t a_total_count_so_far) = 0;
};

The second step is to create a multi-thread protector. The design of all protector is always the same:

• Do not implement the interface to be protected.
• Keep custody of the original non-thread-safe interface implementation.
• Provide multi-thread protection, usually with a mutex.

The reason not to implement the desired interface is that the multi-thread protector is not meant to be used directly. If it doesn’t have the interface, it can’t be used accidentally as the interface.

Its implementation will still mimic the interface very closely. The difference is that each corresponding function will take a lock on the mutex and call the original, non-thread-safe interface. This is how it is protected against the multiple threads.

Here is the example for the progress_t interface:

    // Wrap a non-thread-safe progress in a multi-thread-safe progress.
//
// The progress can only be reported by a per-thread-progress referencing

{
// Wrap a non-threas safe progress.

// Report the final progress tally when destroyed.

// Force to report the progress tally.

// Clear the progress.
void clear_progress() { my_total_count_so_far = 0; }

protected:

// Propagate the progress to the non-thread-safe progress.

private:
size_t               my_report_every = 100 * 1000;
std::atomic  my_total_count_so_far = 0;
std::mutex           my_mutex;

};

The important functions are: update_progress_from_thread() and report_to_non_thread_safe_progress(). The first one receives the progress from each per-thread progress implementation that will be shown later. It accumulates the total in a multi-thread-safe variable and only reports on it when it crosses a given threshold. The second function forwards the progress to the non-thread-safe implementation under the protection of a mutex. Here's the implementation for both:

    void multi_thread_progress_t::update_progress_from_thread(size_t a_count_from_thread)
{
return;

const size_t post_count = pre_count + a_count_from_thread;

if ((pre_count / my_report_every) != (post_count / my_report_every))
{
}
}

{
std::lock_guard lock(my_mutex);
}

The final part of the pattern is the thin per-thread implementation of the interface. In this case we do want to implement the interface. This will be what replaces the original, non-thread-safe implementation. Note that it doesn’t need to be thread-safe! It is meant to be used by a single thread and the multi-thread protection is done in the multi-thread protector that we have shown before.

This division of labor between the protector and the per-thread part greatly simplifies reasoning around the code and simplifies the code itself.

Here is the declaration of the per-thread progress in the example:

    // Report the progress of work from one thread to a multi-thread progress.
//
// Create one instance in each thread. It caches the thread progress and
// only report from time to time to the multi-thread progress to avoid
// accessing the shared atomic variable too often.

{
// Create a per-thread progress that report to the given multi-thread progress.
: progress_t(a_mt_progress.my_report_every / 10), my_mt_progress(&a_mt_progress) {}

: progress_t(an_other), my_mt_progress(an_other.my_mt_progress) { clear_progress(); }

{
progress_t::operator=(an_other);
// Avoid copying the per-thread progress accumulated.
clear_progress();
return *this;
}

// Report the final progress tally when destroyed.

protected:
// Propagate the progress to the multi-thread progress.
void update_progress(size_t a_total_count_so_far) override
{
if (!my_mt_progress)
return;

clear_progress();
}

private: