template<typename T>
class gatb::core::system::impl::ThreadObject< T >
Facility to share a common resource between several threads.
When using multithreading, one has to take care about reads/writes on a resource T by several threads at the same time.
There are two ways to cope with this:
- using some synchronization mechanism (see ISynchronizer); each time the resource T is accessed, one has to lock the synchronizer before the access and unlock the synchronizer after the access
- using local information in each thread instead of accessing the T shared resource; at the end of the threads, one has to use all the gathered local information to update the T resource in a serial way.
The ThreadObject class provides a generic way to follow the second approach. One provides the shared resource to it, then the resource is cloned in N threads and each cloned resource can be locally accessed within its thread without needing synchronization process. At the end of the threads, the ThreadObject provides a way to get each cloned local resource and so the user can update the original resource with the gathered information.
It is possible to give no initial resource to a ThreadObject instance; in such a case, a default original resource is created by using the default constructor of the type of the resource.
Sample of use:
ThreadObject<int> sum;
dispatcher.iterate (it, [&] (int i)
{
sum() += i;
});
sum.foreach ([&] (int localSum)
{
*sum += localSum;
});