NeoPZ
pzparallel.h
Go to the documentation of this file.
1 #include <unistd.h>
2 #include <pthread.h>
3 
4 namespace pz {
5  // util - return the number of cores on linux and macosx
7  return sysconf(_SC_NPROCESSORS_ONLN);
8  }
9 
10  template <typename body_t>
11  struct thread_arg {
12  int i;
13  body_t *obj;
14  };
15 
16  template <typename body_t>
17  static void *thread_work(void *parm) {
19  (*arg->obj)(arg->i);
20  return NULL;
21  }
22 
23  template <typename body_t>
24  void parallel_for(int n, body_t &obj) {
25  // get the number of cores
27  // case the number of threads is lower than the cores
28  if(nthreads > n)
29  nthreads = n;
30  // allocate threads
31  pthread_t *threads = new pthread_t[nthreads];
33  // create args and threads
34  for (int t = 0; t < nthreads; t++) {
35  args[t].i = t;
36  args[t].obj = &obj;
37  pthread_create(&threads[t], NULL, thread_work<body_t>, (void*) &args[t]);
38  }
39  // syncronize all threads
40  for (int t = 0; t < nthreads; t++)
41  pthread_join(threads[t], NULL);
42  // free memory
43  delete [] threads;
44  delete [] args;
45  }
46 
47 } // namespace
list threads
Definition: test.py:140
Definition: pzparallel.h:4
body_t * obj
Definition: pzparallel.h:13
int nthreads
Definition: numatst.cpp:315
void parallel_for(int n, body_t &obj)
Definition: pzparallel.h:24
int get_number_of_cores()
Definition: pzparallel.h:6
static void * thread_work(void *parm)
Definition: pzparallel.h:17