| 1 |
# Background |
| 2 |
|
| 3 |
In Python, multithreading is ineffective at concurrency for CPU bound tasks due |
| 4 |
to the GIL (global interpreter lock). Extension modules can release the GIL in |
| 5 |
CPU bound tasks, but that isn't an option in pure Python. Users use libraries |
| 6 |
such as multiprocessing, subprocess, concurrent.futures.ProcessPoolExecutor, |
| 7 |
etc, to work around the GIL. These modules call `fork()` underneath the hood. |
| 8 |
Various issues have been reported when using these modules with gRPC Python. |
| 9 |
gRPC Python wraps gRPC core, which uses multithreading for performance, and |
| 10 |
hence doesn't support `fork()`. Historically, we didn't support forking in gRPC, |
| 11 |
but some users seemed to be doing fine until their code started to break on |
| 12 |
version 1.6. This was likely caused by the addition of background c-threads and |
| 13 |
a background Python thread. |
| 14 |
|
| 15 |
# Current Status |
| 16 |
|
| 17 |
gRPC Python applications can enable client-side forking when two environment |
| 18 |
variables are given: |
| 19 |
|
| 20 |
``` |
| 21 |
export GRPC_ENABLE_FORK_SUPPORT=true |
| 22 |
export GRPC_POLL_STRATEGY=poll |
| 23 |
``` |
| 24 |
|
| 25 |
The fork-support effort only works with "epoll1" and "poll" polling strategy. |
| 26 |
There is no active development to extend fork-support's coverage. |
| 27 |
|
| 28 |
For more details about poll strategy setting, see |
| 29 |
https://github.com/grpc/grpc/blob/master/doc/environment_variables.md. |
| 30 |
|
| 31 |
# Alternative: use after fork |
| 32 |
|
| 33 |
Complexities mentioned in the background section are inevitable for "pre-fork" |
| 34 |
usage, where the application creates gRPC Python objects (e.g., client channel) |
| 35 |
before invoking `fork()`. However, if the application only instantiate gRPC |
| 36 |
Python objects after calling `fork()`, then `fork()` will work normally, since |
| 37 |
there is no C extension binding at this point. This idea is demonstrated by the |
| 38 |
[multiprocessing |
| 39 |
example](https://github.com/grpc/grpc/tree/master/examples/python/multiprocessing). |