| gclib 1.34.15 Communications API for Galil controllers and PLCs |

Thread Safety

# The Basics

- The easiest way to multithread, and/or to use multiple applications to access the same hardware, is to communicate through gcaps.
- Just leave out `-d` and `--direct` in your GOpen() address and gcaps will be used.
- Each thread, and each application, should use their own GCon handle. In the higher-level Language Support, each thread or application should manage their own gclib object. Don't pass the connection handle between threads.

# The Formalism

gclib supports multi-threaded operation with the following operational definitions.

## gclib is "reentrant"

Reentrant means that a given gclib function call may be invoked in multiple threads when passed distinct arguments. For example, GCommand() may be called simultaneously in different threads so long as the following arguments have unique values, indicating they point to unique memory.

- GCon `g`, the connection must be unique.
- GBufOut `buffer`, the writable buffer must be unique.
- GSize * `bytes_returned`, the writable value must be unique.

## gclib is not "thread-safe"

Thread safety would imply that a given gclib function call could be invoked in multiple threads when passed the same arguments. This mode of operation is not supported by gclib. In other words, it is not safe to call GCommand() simultaneously in different threads if any mutable arguments point to the same memory.

In short, it is not safe to call GCommand() in multiple threads to the same physical connection.

If such operation is required, it is the user's responsibility to use a mutual exclusion (mutex) or other mechanism to protect memory.

## Multi-threaded access to the same connection with gcaps

gcaps provides a multiplexing capability to Galil hardware. When using gcaps, it is therefore safe to call GCommand() in multiple threads to the same physical connection (though not the same GCon value). gclib can connect multiple times to the same Galil connection through gcaps. Because the GCon variable is unique, the reentrant capability of gclib can be used to communicate to the same physical connection through gcaps.