Xmipp  v3.23.11-Nereus
Public Member Functions | List of all members
Barrier Class Reference

#include <xmipp_threads.h>

Public Member Functions

 Barrier (int numberOfThreads)
 
 ~Barrier ()
 
void wait ()
 

Detailed Description

Class to synchronize several threads in some point of execution. Threads is a way of distributing workload across different workers to solve a problem faster. Nevertheless, sometimes we need synchronization between threads to avoid undesired race conditions and other problems. Here we are an implementation of a barrier that allows putting all threads to wait at a given point until all of them have reached such point and can continue working. Barriers are usually available through pthreads system library. Nonetheless, sometimes it is not so we have to implement it here.

//Then in each thread to access the critical section:
mutex.lock();
//...Do critical section stuff
mutex.unlock();

Definition at line 150 of file xmipp_threads.h.

Constructor & Destructor Documentation

◆ Barrier()

Barrier::Barrier ( int  numberOfThreads)

Constructor of the barrier to initialize the object. You should pass the number of working threads that you want to wait on the barrier. The internal counter of the barrier will be initialized with numberOfThreads + 1 taking into account the main thread, so it need to wait also in the barrier with the worker threads to all can move on.

//For synchronize 10 threads created by a main thread
//you can create the barrier from the main thread
Barrier * barrier = new Barrier(10);
//...
//In the synchronization point
barrier->wait();

Definition at line 97 of file xmipp_threads.cpp.

98 {
99  needed = numberOfThreads;
100  called = 0;
101  condition = new Condition();
102 }

◆ ~Barrier()

Barrier::~Barrier ( )

Destructor to free all memory used

Definition at line 104 of file xmipp_threads.cpp.

105 {
106  delete condition;
107 }

Member Function Documentation

◆ wait()

void Barrier::wait ( )

Request to wait in this meet point. For each thread calling this function the execution will be paused until all threads arrive this point.

Definition at line 109 of file xmipp_threads.cpp.

110 {
111  condition->lock();
112  ++called;
113  if (called == needed)
114  {
115  called = 0;
116  condition->broadcast();
117  }
118  else
119  condition->wait();
120  condition->unlock();
121 }
void unlock()
void broadcast()

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