MIRA
Threads

Contents

Overview

For threading, we use boost::thread, which provides classes and functions for managing the threads themselves, along with others for synchronizing data between the threads or providing separate copies of data specific to individual threads.

MIRA provides a few additional helper classes like CyclicRunnable, a class that allows to execute a certain function or operation repeatedly with an exact predefined interval.

The ThreadMonitor is a class that provides an overview of all threads and collects information about the resources of all running threads. Using the ThreadMonitor, threads can be named to provide more information and better debugging.

In the following we give specify some common procedures for tasks that programmers have to deal with very often.

Synchronization

When using multi-threading programming, certain pieces of code (critical sections) may need to be protected to avoid the simultaneous use of a common resources (e.g. a member variable, etc.) from different threads.

To create a code section that is protected from simultanious usage, you can use boost::mutex. Mutexes usually need to be locked when entering the critical section and they must be unlocked when leaving the critical section. If thread A tries to enter a critical section that is locked by another thread B already, then thread A will block at the beginning of the critical section, until thread B has left it:

class MyClass {
boost::mutex mMutex;
public:
void foo() {
// enter the critical section
mMutex.lock(); // other threads may block here, if a thread is already within this section
... do the exclusive stuff here ...
mMutex.unlock(); // leave the critical section and unlock mutex
}
};

In order to make the usage of mutexes even easier and safer, boost provides the boost::mutex::scoped_lock class. This class locks the mutex when it is constructed and automatically unlocks its when it goes out of scope and is destructed. The above example is then simplified to:

void foo() {
// enter the critical section
boost::mutex::scoped_lock lock(mMutex);
... do the exclusive stuff here ...
}

The mutex will be unlocked automatically when the method is left or when an exception occurs. Hence, using boost::mutex::scoped_lock helps to improve exception safety.

Timing

Sometimes it is necessary to pause the execution of the current thread for a specified time. For this reason you can use boost::this_thread::sleep(), for example:

// Stops execution for 3 seconds
boost::this_thread::sleep(Duration::seconds(3))
// Stops execution for 50 milliseconds
boost::this_thread::sleep(Duration::milliseconds(50))

The MIRA_SLEEP macro can also be used to interrupt the current thread for a specified time, e.g:

// Stops execution for 50 milliseconds

If you want to execute a certain function or operation repeatedly with an exact predefined interval use the CyclicRunnable helper class.