chiark / gitweb /
do not have threads at all if NPROCESSORS=1
[moebius2.git] / parallel.c
1 /*
2  * Parallel processing
3  */
4
5 #include <pthread.h>
6
7 #include "mgraph.h"
8 #include "parallel.h"
9
10 typedef struct {
11   const struct Vertices *vertices;
12   Computation *separately;
13   void *gendata;
14 } ForAllThreads;
15
16 typedef struct {
17   ForAllThreads *allthreads;
18   int section;
19   void *secdata;
20   pthread_t thread;
21 } PerThread;
22
23 #if NPROCESSORS != 1
24 static void *routine(void *thread_v) {
25   PerThread *t= thread_v;
26   ForAllThreads *a= t->allthreads;
27
28   a->separately(a->vertices, t->section, t->secdata, a->gendata);
29
30   return 0;
31 }
32 #endif
33
34 void inparallel(const struct Vertices *vertices,
35                 Computation *separately,
36                 Computation *combine,
37                 size_t secdatasz, void *gendata) {
38   typedef struct { unsigned char secdata[secdatasz]; } SecData;
39
40   ForAllThreads allthreads;
41   SecData secdatas[nsections];
42
43   allthreads.vertices= vertices;
44   allthreads.separately= separately;
45   allthreads.gendata= gendata;
46
47 #if NPROCESSORS != 1
48   PerThread threads[nsections];
49   int s, r;
50
51   for (s=0; s<nsections; s++) {
52     threads[s].allthreads= &allthreads;
53     threads[s].section= s;
54     threads[s].secdata= secdatas[s].secdata;
55     r= pthread_create(&threads[s].thread,0,routine,&threads[s]);
56     if (r) diee("pthread_create");
57   }
58
59   for (s=0; s<nsections; s++) {
60     r= pthread_join(threads[s].thread, 0);
61     if (r) diee("pthread_join");
62     combine(vertices, s, threads[s].secdata, gendata);
63   }
64 #else
65   separately(vertices, 0, &secdatas[0], gendata);
66   combine(vertices, 0, &secdatas[0], gendata);
67 #endif
68 }