| gclib 424 Communications API for Galil controllers and PLCs |

threading.md
1 # Thread Safety {#threading}
2
3 ## The Basics
4
5 - The easiest way to multithread, and/or to use multiple applications to
6 access the same hardware, is to communicate through @ref gcaps.
7
8 - Just leave out `-d` and `--direct` in your GOpen() address and gcaps will
9 be used.
10
11 - Each thread, and each application, should use their own @ref GCon handle.
12 In the higher-level @ref languages, each thread or application should manage their
13 own gclib object. Don't pass the connection handle between threads.
14
15 ## The Formalism
16
17 gclib supports multi-threaded operation with the following operational definitions.
18
19 ### gclib is "reentrant"
20
21 Reentrant means that a given gclib function call may be invoked in multiple threads when passed distinct arguments.
22 For example, GCommand() may be called simultaneously in different threads so long as the following arguments have
23 unique values, indicating they point to unique memory.
24
25 * \link GCon \endlink `g`, the connection must be unique.
26 * \link GBufOut \endlink `buffer`, the writable buffer must be unique.
27 * \link GSize \endlink * `bytes_returned`, the writable value must be unique.
28
29
30 ### gclib is **not** "thread-safe"
31
32 Thread safety would imply that a given gclib function call could be invoked in multiple threads when passed *the same* arguments.
33 This mode of operation **is not** supported by gclib. In other words, it is not safe to call GCommand() simultaneously in
34 different threads if any mutable arguments point to the same memory.
35
36 In short, it is **not** safe to call GCommand() in multiple threads to the same physical connection.
37
38 If such operation is required, it is the user's responsibility to use a mutual exclusion (mutex) or other mechanism to protect memory.
39
40 ### Multi-threaded access to the same connection with gcaps
41
42 @ref gcaps provides a multiplexing capability to Galil hardware. When using gcaps,
43 it is therefore safe to call GCommand() in multiple threads to the *same physical connection* (though not the same \link GCon \endlink value).
44 gclib can connect multiple times to the same Galil connection through gcaps. Because the \link GCon \endlink variable is unique, the
45 reentrant capability of gclib can be used to communicate to the same physical connection through gcaps.