A library for working with phylogenetic and population genetic data.
v0.32.0
ThreadCriticalSection< Tag > Class Template Reference

#include <genesis/utils/threading/thread_functions.hpp>

Detailed Description

template<typename Tag>
class genesis::utils::ThreadCriticalSection< Tag >

Helper class to define a critical section.

This is similar to #pragma omp critical, in order to synchronize access to a criticla section across multiple threads. The class internally uses a std::mutex to guarantee exclusive access for each thread.

The class is templated with a Tag, so that mutiple independent sections can be defined, each getting their own mutex. The usage for this class is hence to first define the access tag, and then use it as follows:

// Define section tag
struct MyThreadCriticalSection{};

// Start a critical section
{
ThreadCriticalSection<MyThreadCriticalSection> cs;

// Critical section code for MyThreadCriticalSection
std::cout << "Task " << id << " is running in MyThreadCriticalSection." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(100));

} // MyThreadCriticalSection mutex is automatically released here

To simplify this, instead of having to define the tag struct each time, we also provide a macro GENESIS_THREAD_CRITICAL_SECTION(TagName) to this end:

// Start a critical section
{
GENESIS_THREAD_CRITICAL_SECTION(MyThreadCriticalSection)
//...
}

This can however not be used if multiple sections need to be synchronized with the same tag, as the macro would define the same struct multiple times; depending on the scope, this leads either to a multiple definition error, or to structs that are local to their scope, and hence lead to sections that do not synchronize with each other. In that case, use the above instead, with a tag struct that is defined in a fitting scope that is visible to all sections that need to be protected by it.

Definition at line 439 of file thread_functions.hpp.

Public Member Functions

 ThreadCriticalSection ()
 
 ~ThreadCriticalSection ()
 

Constructor & Destructor Documentation

◆ ThreadCriticalSection()

Definition at line 443 of file thread_functions.hpp.

◆ ~ThreadCriticalSection()

~ThreadCriticalSection ( )
inline

Definition at line 448 of file thread_functions.hpp.


The documentation for this class was generated from the following file: