DHPS-Solutions / dhps-lib

c+
3 stars 0 forks source link

thread safety #18

Open LytixDev opened 1 year ago

LytixDev commented 1 year ago

Some data structures should perhaps be thread safe?

For example the hashmap implementation should have a way to ensure it is safe to use with multiple threads. It could be as simple as having one single mutex locking the entire hashmap. We could also have a mutex that only locks on hashmap_put.

In order to not add the overhead of thread safety when its not needed, the user should define whether or not they want the implementation to be thread safe.

// user writes
#define HASHMAP_THREAD_SAFE

...

struct hashmap_t {
    struct bucket_t *buckets;
    uint32_t size_log2;
    size_t len;
#ifdef HASHMAP_THREAD_SAFE
   mutex_t lock;
#endif
};

void hashmap_put()
{
#ifdef HASHMAP_THREAD_SAFE
    // acquire lock
#endif

   / / code

#ifdef HASHMAP_THREAD_SAFE
    // release lock
#endif
}

s
callumgran commented 1 year ago

I very much like this idea! I also suggest creating a threadpool that could be used to exemplify how useful this is.

callumgran commented 1 year ago

I believe we could use a common struct for thread safety. This struct would have a condition predicate, a lock and a condition variable. This way it could also broadcast conditions and only be in effect if the predicate is true, etc etc.

struct condition_t {
    bool cond_predicate;
    pthread_mutex_t cond_lock;
    pthread_cond_t cond_variable;
};