JavaProphet
JavaProphet

Reputation: 991

If I have one thread writing and many reading, how can I only lock when writing, but not reading?

So I have this structure to a cache I'm writing:

struct scache {
        char* rp;
        int ce;
        char* code;
        struct headers* headers;
        struct body* body;
};

struct dcache {
        unsigned char md5[16];
        struct scache scache;
};

struct cache {
        struct scache** scaches;
        size_t scache_size;
        struct dcache** dcaches;
        size_t dcache_size;
};

struct scache* getSCache(struct cache* cache, char* rp, int ce);

struct dcache* getDCache(struct cache* cache, char* rp, int ce, unsigned char* md5);

int addSCache(struct cache* cache, struct scache* scache);

int addDCache(struct cache* cache, struct dcache* dcache);

I want to use mutexes so that I can not allow any reading when I'm writing, but not have reads block other reads. So reading threads do not block each other, but if one adds one, it'll block other writes and reads.

I looked into mutexes, but I can't wrap my mind around how to implement this right. I think I could just lock the writing, but then what if a read see's the size larger or smaller than it really is, then under reads or over reads, both causing issues with double caching or memory corruption.

Upvotes: 0

Views: 97

Answers (1)

Šimon Tóth
Šimon Tóth

Reputation: 36441

What you want is a read-write lock. There are different implementation depending on which way they are biased.

The two border extremes are:

  • writes get immediate access
  • writes get access only if there 0 reads waiting

Most implementations are somewhere in the middle biased towards writes or reads.

For a standard POSIX implementation see: pthread_rwlock_t http://pubs.opengroup.org/onlinepubs/007908799/xsh/pthread_rwlock_init.html

Upvotes: 3

Related Questions