You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/source/working/multiprocessing.rst
+4-94Lines changed: 4 additions & 94 deletions
Original file line number
Diff line number
Diff line change
@@ -3,15 +3,9 @@
3
3
Multiprocessing
4
4
===============
5
5
6
-
.. warning::
7
-
8
-
If using btrdb-python with multiprocessing, you must fork (e.g. start your workers)
9
-
before creating a connection to the database, otherwise the gRPC connection will
10
-
hang. See: https://github.com/grpc/grpc/issues/15334 for details.
11
-
12
6
Complex analytics in Python may require additional speedups that can be gained by using the Python multiprocessing library. Other libraries like web applications take advantage of multiprocessing to serve a large number of users. Because btrdb-python uses `grpc <https://grpc.io/docs/tutorials/basic/python.html>`_ under the hood, it is important to understand how to connect and reuse connections to the database in a multiprocess or multithread context.
13
7
14
-
The first and most critical thing to note is that ``btrdb.Connection`` objects *are not thread- or multiprocess-safe*. This means that in your code you should use either a lock or a semaphore to share a single connection object or that each process or thread should create their own connection object and clean up after themselves when they are done using the connection. Moreover, because of the forking issue discribed in the warning above, you must also take care when to create connections in worker processes.
8
+
The most critical thing to note is that ``btrdb.Connection`` objects *are not thread or multiprocess-safe*. This means that in your code you should use either a lock or a semaphore to share a single connection object or that each process or thread should create their own connection object and clean up after themselves when they are done using the connection.
15
9
16
10
Let's take the following simple example: we want to perform a data quality analysis on 12 hour chunks of data for all the streams in our ``staging/sensors`` collection. If we have hundreds of sensor streams across many months, this job can be sped up dramatically by using multiprocessing. Instead of having a single process churning through the each chunk of data one at a time, several workers can process multiple data chunks simultanously using multiple CPU cores and taking advantage of other CPU scheduling optimizations.
17
11
@@ -66,7 +60,7 @@ Consider the processing architecture shown in :numref:`architecture`. At first g
@@ -82,90 +76,6 @@ Consider the processing architecture shown in :numref:`architecture`. At first g
82
76
83
77
Let's break this down quickly since this is a very common design pattern. First the ``time_ranges`` function gets the earliest and latest timestamp from a stream, then returns all 12 hour intervals between those two timestamps with no overlap. An imaginary ``stream_quality`` function takes a uuid for a stream, connects to the database and then applies the example ``data_quality`` method to all 12 hour chunks of data using the ``time_ranges`` method, returning a JSON string with the results.
84
78
85
-
We expect the ``stream_quality`` function to be our parallelizable function (e.g. computing the data quality for multiple streams at a time). Depending on how long the ``data_quality`` function takes to compute we may also want to parallelize ``(stream, start, end)`` tuples. It seems that the ``multiprocessing.Pool`` would be perfect for this.
86
-
87
-
The problem, however, occurs because in order to get the UUIDs of the streams to queue to the ``Pool``, we must first connect to the database and perform a search on the specified collection. This connection appears before the fork (which occurs when ``imap_unordered`` is called) and therefore gRPC fails. Unfortunately this means we have to be a bit more verbose.
88
-
89
-
The solution is to create a custom worker that connects to BTrDB after the fork. Unfortunately, at the time of this writing there is no way to pass a custom worker to the ``Pool`` object. The worker is as follows:
# connect when started to ensure connection is in the fork
110
-
self.connect()
111
-
112
-
whileTrue:
113
-
task =self.tasks.get()
114
-
if task isNone:
115
-
# poison pill means shutdown
116
-
return
117
-
118
-
try:
119
-
# Pass the task to the handler
120
-
result =self.handler(task)
121
-
exceptExceptionas e:
122
-
# Send any exceptions back to main process
123
-
result = {"task": task, "error": str(e)}
124
-
125
-
self.results.put_nowait(result)
126
-
127
-
This simple worker process accepts BTrDB connection arguments, the URL and API key to connect to the database as well as a handler function and tasks and resuls queues. It only connects to the database on ``run()``, ensuring that the connection occurs after the fork. Then it simply reads off the task queue, executing the task and putting the results (or exceptions) on the results queue. If it gets ``None`` from the tasks queue, it shuts down.
128
-
129
-
We can change our multiprocessing method to use this new worker and connect after fork as follows:
# Start the workers, this is where the fork occurs
149
-
for worker in workers:
150
-
worker.start()
151
-
152
-
# Now we can connect to the database and enqueue the streams
153
-
n_tasks =0
154
-
db = btrdb.connect(HOST, apikey=APIKEY)
155
-
for stream in db.streams_in_collection("staging/sensors"):
156
-
tasks.put_nowait(stream.uuid)
157
-
n_tasks +=1
158
-
159
-
# Enqueue the poison pill to shut the workers down
160
-
for _ inrange(len(workers)):
161
-
tasks.put_nowait(None)
162
-
163
-
# Begin reading off of the results queue
164
-
for _ inrange(n_tasks):
165
-
print(results.get())
166
-
167
-
# Join on the workers to ensure they clean up
168
-
for worker in workers:
169
-
worker.join()
79
+
The ``stream_quality`` function is our parallelizable function (e.g. computing the data quality for multiple streams at a time). Depending on how long the ``data_quality`` function takes to compute, we may also want to parallelize ``(stream, start, end)`` tuples.
170
80
171
-
This method is certainly a lot more verbose than using `mp.Pool`, but unfortunately is the only work around to the forking issue that exists in BTrDB. If you would like features like a connection pool object (as other databases have) or multiprocessing helpers, please leave us a note in our GitHub issues!
81
+
If you would like features like a connection pool object (as other databases have) or multiprocessing helpers, please leave us a note in our GitHub issues!
0 commit comments