Ken Y-N
Ken Y-N

Reputation: 15009

Using N threads or N-1 threads

I've come across code that looks like this in more than one place in some code I have inherited:

const size_t N = 4;
FOO data[N];
boost::thread_group all_threads;
for(size_t i = 0; i < N-1; i++)
{
    all_threads.create_thread(processData, data[i]);
}
processData(data[N-1]);
all_threads.join_all();

For N tasks, create N-1 threads and do the last data item in the main thread. Ignoring issues about creating too many threads (N is always either 4 or 8) is there any merit in this rather than just creating N threads in the loop? From my perspective, having two different invocation methods for processData means two places to change if the parameters update, and reading the code there's the extra cognitive load to check that we really are doing the Nth call correctly.

Upvotes: 1

Views: 270

Answers (1)

eerorika
eerorika

Reputation: 238341

Creating a thread has overhead. Thus, avoiding the creation of a thread has some merit.

Whether that merit is significant, depends on the use case. For small inputs, a single thread will be more optimal than a parallel implementation. For large inputs, the effect of creating a single thread will be insignificant. Between those extremes, there is likely to be an interval of input sizes where the creation of a single thread is significant. It may be a small interval.

Conclusion: Creating N threads for symmetric simplicity can be reasonable. If you measure that thread creation takes a significant portion of execution time, then consider the described N-1 technique or even single-threaded implementation.

Upvotes: 2

Related Questions