Douglas Santos
Douglas Santos

Reputation: 37

Is GLib's GHashTable thread-safe for read-only accesses from multiple threads?

I want to create a GHashTable in program's initialization, which would be later concurrently accessed for reading only by newly created threads.

Is it safe to do so without a lock?

Upvotes: 1

Views: 349

Answers (2)

davmac
davmac

Reputation: 20631

Strictly speaking, C makes no guarantees, unless you have some sort of synchronisation, that data written by one thread is going to be visible or coherent to others.

You need a memory operation with "release" semantics after setting up the hash table, and one with "acquire" semantics in the other threads before they read it.

It's probably enough that the reading threads are created after the hash table is created, though I'm not 100% certain of this.

Upvotes: 1

Barmar
Barmar

Reputation: 780974

In general, mutual exclusion is only needed when you could be modifying data concurrently with reading or modifying in another thread. If all accesses (after the hash table is filled in during initialization) are just reading, there's no need for locks.

Upvotes: 3

Related Questions