www.mooseframework.org
ParallelUniqueId.h
Go to the documentation of this file.
1 //* This file is part of the MOOSE framework
2 //* https://www.mooseframework.org
3 //*
4 //* All rights reserved, see COPYRIGHT for full restrictions
5 //* https://github.com/idaholab/moose/blob/master/COPYRIGHT
6 //*
7 //* Licensed under LGPL 2.1, please see LICENSE for details
8 //* https://www.gnu.org/licenses/lgpl-2.1.html
9 
10 #pragma once
11 
12 #include "MooseTypes.h" // included for namespace usage and THREAD_ID
13 
14 #include "libmesh/libmesh_common.h"
15 #include "libmesh/threads.h"
16 
17 #ifdef LIBMESH_HAVE_TBB_API
18 #include "tbb/concurrent_queue.h"
19 #include "tbb/tbb_thread.h"
20 #elif LIBMESH_HAVE_OPENMP
21 #include <omp.h>
22 #elif LIBMESH_HAVE_PTHREAD
23 #include <queue>
24 #include "MooseException.h"
25 #endif
26 
27 using namespace libMesh;
28 
30 {
31 public:
33  {
34 #ifdef LIBMESH_HAVE_TBB_API
35  _ids.pop(id);
36 #elif LIBMESH_HAVE_OPENMP
37  id = omp_get_thread_num();
38 #elif LIBMESH_HAVE_PTHREAD
39  Threads::spin_mutex::scoped_lock lock(_pthread_id_mutex);
40 
41  if (_ids.empty())
42  throw MooseException(
43  "No Thread IDs available in ParallelUniqueID. Did you forget to initialize()?");
44 
45  id = _ids.front();
46  _ids.pop();
47 #else
48  // There is no thread model active, so we're always on thread 0.
49  id = 0;
50 #endif
51  }
52 
54  {
55 #ifdef LIBMESH_HAVE_TBB_API
56  _ids.push(id);
57 #elif !defined(LIBMESH_HAVE_OPENMP) && defined(LIBMESH_HAVE_PTHREAD)
58  Threads::spin_mutex::scoped_lock lock(_pthread_id_mutex);
59 
60  _ids.push(id);
61 #endif
62  }
63 
68  static void initialize()
69  {
70  if (!_initialized)
71  {
72  _initialized = true;
73 
74 #if defined(LIBMESH_HAVE_TBB_API) || \
75  (!defined(LIBMESH_HAVE_OPENMP) && defined(LIBMESH_HAVE_PTHREAD))
76  for (unsigned int i = 0; i < libMesh::n_threads(); ++i)
77  _ids.push(i);
78 #endif
79  }
80  }
81 
83 
84 private:
85 #ifdef LIBMESH_HAVE_TBB_API
86  static tbb::concurrent_bounded_queue<unsigned int> _ids;
87 #elif !defined(LIBMESH_HAVE_OPENMP) && defined(LIBMESH_HAVE_PTHREAD)
88  static std::queue<unsigned int> _ids;
89  static Threads::spin_mutex _pthread_id_mutex;
90 #endif
91 
92  static bool _initialized;
93 };
94 
static void initialize()
Must be called by main thread before any threaded computation! Do NOT call in a worker thread! ...
static tbb::concurrent_bounded_queue< unsigned int > _ids
The following methods are specializations for using the libMesh::Parallel::packed_range_* routines fo...
static bool _initialized
static Threads::spin_mutex _pthread_id_mutex
Provides a way for users to bail out of the current solve.
static std::queue< unsigned int > _ids
unsigned int THREAD_ID
Definition: MooseTypes.h:161