I have a single board computer with a I2C GPIO expander device, listed as /dev/i2c-0. In my multithreaded program I open() this character device and read/write to it on separate threads using i2c_smbus_write_byte_data and friends from the libi2c library, but I am not sure if that is thread-safe.
I have seen kernel space GPIO driver implementations that bind over the I2C character device and allow to interface with the device as if it was a GPIO device (pca953x driver) and they have internal mutexes within every gpio_set/get function. In another question people say i2c_smbus_* functions have internal mutexes so I cannot be sure.
Is this kind of concurrent access thread-safe?
void *thread_fn(void *arg){
int fd = *(int*)arg;
uint16_t d;
for(uint16_t i=0;i<1000;i++) {
if (i%2==0){
d = i2c_smbus_read_word_data(fd, REG);
} else {
d |= 1 << (i%16);
i2c_smbus_write_word_data(fd, REG, d);
}
}
return NULL;
}
int main(void){
int fd = open("/dev/i2c-0");
pthread_t t;
pthread_create(&t, NULL, thread_fn, &fd);
for(uint16_t i=0;i<1000;i++)
i2c_smbus_write_word_data(fd, REG, i);
pthread_join(t, NULL);
return 0;
}