| 1 |
## Multithreading {#threads} |
| 2 |
|
| 3 |
The @ref pn_proactor allows you to create multi-threaded client and server |
| 4 |
applications. You can call `pn_proactor_run` in multiple threads to create a |
| 5 |
thread pool for proton to handle events and IO. |
| 6 |
|
| 7 |
The @ref proactor functions are safe to call from any thread. Most other |
| 8 |
functions are **not** safe to call concurrently. The following rules applies: |
| 9 |
objects and events associated with *different* connections can safely be used |
| 10 |
concurrently. Objects and events associated with *the same* connection cannot. |
| 11 |
|
| 12 |
The proactor helps you to handle connections safely: `pn_proactor_get()` and |
| 13 |
`pn_proactor_wait()` will never return events associated with the same |
| 14 |
connection to different threads concurrently. As long as you process only the |
| 15 |
objects available from the event returned by the proactor, you are in no danger. |
| 16 |
|
| 17 |
When you need to process objects belonging to a *different* connection (for |
| 18 |
example if you receive a message on one connection and want to send it on |
| 19 |
another) you must use locks and thread safe data structures and the |
| 20 |
`pn_connection_wake()` function. |
| 21 |
|
| 22 |
### The wake function |
| 23 |
|
| 24 |
`pn_connection_wake()` can be called from any thread as long as the |
| 25 |
`pn_connection_t` has not been freed. It allows any thread to "wake up" a |
| 26 |
connection by generating a @ref PN\_CONNECTION\_WAKE event for that connection. |
| 27 |
|
| 28 |
For example, supposed a message arrives on connection A and must be sent on |
| 29 |
connection B. The thread that receives events for A from the proactor can safely |
| 30 |
call `pn_link_recv()` on A's link to decode the @ref message. However it cannot |
| 31 |
call `pn_link_send()` on any link belonging to B. |
| 32 |
|
| 33 |
The decoded @ref message is independent of any connection, so the thread |
| 34 |
handling A can store the message in a thread-safe data structure, and call |
| 35 |
`pn_connection_wake()` to notify B. Shortly after, some thread will get a @ref |
| 36 |
PN\_CONNECTION\_WAKE event for B, and can retrieve the message and send it |
| 37 |
on B's link. |
| 38 |
|
| 39 |
@note Be careful to ensure (using a mutex for example) that connection B |
| 40 |
cannot be deleted before connection A calls `pn_connection_wake`. Connections |
| 41 |
are automatically deleted by the proactor after the @ref PN\_TRANSPORT\_CLOSED event |
| 42 |
git |