C++ Threading

June 5, 2015 at 05:02 pm

I wanted to process separate data on different threads and get back the results. With C++11, this was quite easy to implement. I originally wrote a threadForEach function and then a ThreadQueue class.

threadForEach

This will process given data on a "thread for each," although it maxes out at a certain number so you don't get a million threads going. If you don't want cores.h (which sets the number of threads to your core count), you can modify threading.h a little bit.

Download
demo.cpp
cores.h
threading.h

Testing Class

[garrett ~]$ g++ demo.cpp -std=c++11 -lpthread -o demo
[garrett ~]$ ./demo
Thread: 0
Thread: 1
...

Using Class

R function(T* item) { }
std::vector<R> results = threadForEach(container<T> items, function);
for (const R& i : results) ...

where container<T> is any container that has .begin(), .end(), and .size().

ThreadQueue

Later on, I wrote a generic thread queue class that would allow the primary thread to continue processing data, adding more items to the queue, while the queue was processing the data. If this is more what you're trying to do, you could take a look at:

Code
threadqueue.h
threadqueuevoid.h
cores.h
cores.cpp

The first works with a function that will return a value, the second with functions not returning anything. The cores.{h,cpp} files are somewhat optional. Just like the thread-for-each function, the thread queue will default to the number of cores you have if you specify a 0 for the core count. If you don't want this functionality, you can slightly modify the files.