1.. _locking: 2 3Locking 4======= 5 6FRR ships two small wrappers around ``pthread_mutex_lock()`` / 7``pthread_mutex_unlock``. Use ``#include "frr_pthread.h"`` to get these 8macros. 9 10.. c:function:: frr_with_mutex(pthread_mutex_t *mutex) 11 12 Begin a C statement block that is executed with the mutex locked. Any 13 exit from the block (``break``, ``return``, ``goto``, end of block) will 14 cause the mutex to be unlocked:: 15 16 int somefunction(int option) 17 { 18 frr_with_mutex(&my_mutex) { 19 /* mutex will be locked */ 20 21 if (!option) 22 /* mutex will be unlocked before return */ 23 return -1; 24 25 if (something(option)) 26 /* mutex will be unlocked before goto */ 27 goto out_err; 28 29 somethingelse(); 30 31 /* mutex will be unlocked at end of block */ 32 } 33 34 return 0; 35 36 out_err: 37 somecleanup(); 38 return -1; 39 } 40 41 This is a macro that internally uses a ``for`` loop. It is explicitly 42 acceptable to use ``break`` to get out of the block. Even though a single 43 statement works correctly, FRR coding style requires that this macro always 44 be used with a ``{ ... }`` block. 45 46.. c:function:: frr_mutex_lock_autounlock(pthread_mutex_t *mutex) 47 48 Lock mutex and unlock at the end of the current C statement block:: 49 50 int somefunction(int option) 51 { 52 frr_mutex_lock_autounlock(&my_mutex); 53 /* mutex will be locked */ 54 55 ... 56 if (error) 57 /* mutex will be unlocked before return */ 58 return -1; 59 ... 60 61 /* mutex will be unlocked before return */ 62 return 0; 63 } 64 65 This is a macro that internally creates a variable with a destructor. 66 When the variable goes out of scope (i.e. the block ends), the mutex is 67 released. 68 69 .. warning:: 70 71 This macro should only used when :c:func:`frr_with_mutex` would 72 result in excessively/weirdly nested code. This generally is an 73 indicator that the code might be trying to do too many things with 74 the lock held. Try any possible venues to reduce the amount of 75 code covered by the lock and move to :c:func:`frr_with_mutex`. 76