Threads

All device drivers written for Gadgeteer will process samples in a thread separate from the Input Manager. We have chosen this design to avoid the complications that often arise from using non-blocking I/O and to allow the drivers to act more as independent entities. Thus, it will be important to understand how to use the VPR thread interface.

First and foremost, developers must always remember that Gadgeteer uses a shared-memory model for all threads, regardless of the underlying platform-specific thread interface. This follows the lightweight thread model set forth by the POSIX threads (pthreads) standard. With a shared-memory model, all threads have access the same memory, and thus it will almost certainly be necessary to control access to shared variables. In most cases, the class vpr::Mutex will provide sufficient control over multi-threaded data access.

Caution

Multi-threaded programming can be tricky, and it is not something that most people can jump into without some background. Those developers who have not done multi-threaded programming before should review a manual or other reference on the topic before beginning work on a new driver. VPR threads are semantically similar to pthreads, and the concepts inherent in multi-threaded programming (e.g., protecting critical sections) will be the same regardless of the specific implementation. To learn more about pthreads specifically, we recommend [Nic96].

Device driver authors will probably not have to do much with shared data access control because the driver will operate almost entirely in the sample loop thread. Any other method invocations (starting the driver, stopping it, configuring it, etc.) will happen in the Input Manager thread, and common memory accesses have pre-defined helper methods to simplify the work of driver authors. These details will be explained further in later chapters.