1 #pragma once
2 
3 #include "sync.hh"
4 #include "util.hh"
5 
6 #include <queue>
7 #include <functional>
8 #include <thread>
9 #include <map>
10 #include <atomic>
11 
12 namespace nix {
13 
14 MakeError(ThreadPoolShutDown, Error)
15 
16 /* A simple thread pool that executes a queue of work items
17    (lambdas). */
18 class ThreadPool
19 {
20 public:
21 
22     ThreadPool(size_t maxThreads = 0);
23 
24     ~ThreadPool();
25 
26     // FIXME: use std::packaged_task?
27     typedef std::function<void()> work_t;
28 
29     /* Enqueue a function to be executed by the thread pool. */
30     void enqueue(const work_t & t);
31 
32     /* Execute work items until the queue is empty. Note that work
33        items are allowed to add new items to the queue; this is
34        handled correctly. Queue processing stops prematurely if any
35        work item throws an exception. This exception is propagated to
36        the calling thread. If multiple work items throw an exception
37        concurrently, only one item is propagated; the others are
38        printed on stderr and otherwise ignored. */
39     void process();
40 
41 private:
42 
43     size_t maxThreads;
44 
45     struct State
46     {
47         std::queue<work_t> pending;
48         size_t active = 0;
49         std::exception_ptr exception;
50         std::vector<std::thread> workers;
51         bool draining = false;
52     };
53 
54     std::atomic_bool quit{false};
55 
56     Sync<State> state_;
57 
58     std::condition_variable work;
59 
60     void doWork(bool mainThread);
61 
62     void shutdown();
63 };
64 
65 /* Process in parallel a set of items of type T that have a partial
66    ordering between them. Thus, any item is only processed after all
67    its dependencies have been processed. */
68 template<typename T>
processGraph(ThreadPool & pool,const std::set<T> & nodes,std::function<std::set<T> (const T &)> getEdges,std::function<void (const T &)> processNode)69 void processGraph(
70     ThreadPool & pool,
71     const std::set<T> & nodes,
72     std::function<std::set<T>(const T &)> getEdges,
73     std::function<void(const T &)> processNode)
74 {
75     struct Graph {
76         std::set<T> left;
77         std::map<T, std::set<T>> refs, rrefs;
78     };
79 
80     Sync<Graph> graph_(Graph{nodes, {}, {}});
81 
82     std::function<void(const T &)> worker;
83 
84     worker = [&](const T & node) {
85 
86         {
87             auto graph(graph_.lock());
88             auto i = graph->refs.find(node);
89             if (i == graph->refs.end())
90                 goto getRefs;
91             goto doWork;
92         }
93 
94     getRefs:
95         {
96             auto refs = getEdges(node);
97             refs.erase(node);
98 
99             {
100                 auto graph(graph_.lock());
101                 for (auto & ref : refs)
102                     if (graph->left.count(ref)) {
103                         graph->refs[node].insert(ref);
104                         graph->rrefs[ref].insert(node);
105                     }
106                 if (graph->refs[node].empty())
107                     goto doWork;
108             }
109         }
110 
111         return;
112 
113     doWork:
114         processNode(node);
115 
116         /* Enqueue work for all nodes that were waiting on this one
117            and have no unprocessed dependencies. */
118         {
119             auto graph(graph_.lock());
120             for (auto & rref : graph->rrefs[node]) {
121                 auto & refs(graph->refs[rref]);
122                 auto i = refs.find(node);
123                 assert(i != refs.end());
124                 refs.erase(i);
125                 if (refs.empty())
126                     pool.enqueue(std::bind(worker, rref));
127             }
128             graph->left.erase(node);
129             graph->refs.erase(node);
130             graph->rrefs.erase(node);
131         }
132     };
133 
134     for (auto & node : nodes)
135         pool.enqueue(std::bind(worker, std::ref(node)));
136 
137     pool.process();
138 
139     if (!graph_.lock()->left.empty())
140         throw Error("graph processing incomplete (cyclic reference?)");
141 }
142 
143 }
144