In this recipe, we will see how to protect data against the concurrent access of two or more processes to avoid race conditions.
Locking with the process context
How to do it...
To present a simple example about how to add a mutex to the chrdev driver, we can make a few modifications to it, as reported in the following.
- First, we have to add the mux mutex to the driver's main structure in the chrdev.h header file, as follows:
/* Main struct */
struct chrdev_device {
char label[NAME_LEN];
unsigned int busy : 1;
char *buf;
int read_only;
unsigned int id;
struct module *owner;
struct cdev cdev;
struct device *dev;
struct mutex mux;
};
All modifications presented here can be applied to the chrdev...