Applying C - Locking |
Written by Harry Fairhead | |||||||
Tuesday, 27 May 2025 | |||||||
Page 3 of 3
Using a mutex is very easy – getting it right can be more difficult. For example, in the previous case of updating a struct the problem is that the struct has to updated atomically. The solution is to make both updates subject to acquiring a lock. That is: pthread_mutex_t my_mutex=PTHREAD_MUTEX_INITIALIZER; void * resetRec(void *p) { for ( j=1;;j++) { pthread_mutex_lock(&my_mutex); strcpy(me.name, "xxxxx"); me.age = 0; pthread_mutex_unlock(&my_mutex); } } The main program does the same thing and locks the update to the struct: int main(int argc, char** argv) { pthread_t pthread; int id = pthread_create(&pthread,NULL, If you try this out you will discover that it still doesn’t work. After a few thousand iterations the program will halt and print xxxxx, 0, 3456. We have stopped the problem of the two updates creating an invalid record, but we haven’t stopped the problem of the struct being changed by the thread during the if statement’s testing of its two fields, name and age. It can be very difficult to ensure that access to shared variables is fully protected. There is a tendency to think that we only have to lock when two threads are trying to perform the same or similar operation on a shared resource. In practice you need to lock whenever a thread accesses a shared resource. To make it all work unlock in the main program has to be moved to after the if. This means that the amount of time that the mutex is unlocked by the main program is very small. Notice that the amount of time that the thread releases the lock is also very small and starvation of the second thread is now very likely. There are some more advanced mutex features. For example, there is the: pthread_mutex_trylock(&mymutex); function which always returns at once, but with an error if the lock hasn’t been acquired. This can be used to allow a thread to get on with some work while it waits for the lock to come free. The default mutex is a fast mutex, which doesn’t check to see which thread locked it when attempting a lock. This means if the same thread tries to lock it a second time it is suspended and it is never able to unlock the mutex. Another type of mutex is a recursive mutex, which counts the number of times a thread has locked it and requires the same number of unlocks to free the mutex. There is also a separate rwlock that can be locked for reading only or for writing only. In Chapter but not in this extract
Summary
Now available as a paperback or ebook from Amazon.Applying C For The IoT With Linux
Also see the companion book: Fundamental C To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.
Comments
or email your comment to: comments@i-programmer.info |
|||||||
Last Updated ( Tuesday, 27 May 2025 ) |