Hello I built a hash table in C. I have unit tested it enough to be confident it works. The thing is that the data structure will be dynamicly linked to code that I did not write and may be using threads. So I need to synchronize it so it’ll work correctly for theoretically any number of threads concurrently modifying/ reading it. After studying the pthread mutex API I did the following
Declared a static global variable:
static pthread_mutex_t lock;
On HashTable_init (which is always called before the hash table is used) I init it:
pthread_mutex_init(&lock,NULL);
On each function that reads/writes the structure I put an lock at start:
pthread_mutex_lock(&lock);
and unlock at the end:
pthread_muter_unlock(&lock);
Is that enough to make an data structure synchronized? ( as at the moment my program hangs ).
Thank you
It might be not enough. With locking each and every method, you ensure that the internal structure of your container is consistent at any point; but some uses of the container might require more than that.
Consider the following rather simple case: in one thread, you found an item by certain key and start editing it. When find() completes, it releases the lock and then returns a reference to an item. Meanwhile the lock can be acquired and another thread might for example delete this item, quite unexpectedly for the first thread.
Designing and developing a good and safe concurrent container is not an easy thing. I would recommend you instead look for ready-to-use solutions.