How to write a "thread safe" function in C ?
Posted
by Andrei Ciobanu
on Stack Overflow
See other posts from Stack Overflow
or by Andrei Ciobanu
Published on 2010-04-03T08:03:54Z
Indexed on
2010/04/03
8:13 UTC
Read the original article
Hit count: 219
c
|thread-safety
Hello I am writing some data structures in C, and I've realized that their associated functions aren't thread safe. The i am writing code uses only standard C, and I want to achieve some sort of 'synchronization'.
I was thinking to do something like this:
enum sync_e { TRUE, FALSE };
typedef enum sync_e sync;
struct list_s {
//Other stuff
struct list_node_s *head;
struct list_node_s *tail;
enum sync_e locked;
};
typedef struct list_s list;
, to include a "boolean" field in the list structure that indicates the structures state: locked, unlocked.
For example an insertion function will be rewritten this way:
int list_insert_next(list* l, list_node *e, int x){
while(l->locked == TRUE){
/* Wait */
}
l->locked = TRUE;
/* Insert element */
/* -------------- */
l->locked = FALSE;
return (0);
}
While operating on the list the 'locked' field will be set to TRUE, not allowing any other alterations. After operation completes the 'locked' field will be again set to 'TRUE'.
Is this approach good ? Do you know other approaches (using only standard C).
© Stack Overflow or respective owner