0

Are g_hash_table_lookup and g_hash_table_insert thread-safe? Can I use code like this:

dict = g_hash_table_new();
for (i = 0; i < N; i++) {
    compute_A();
    find_hash_of_A();
    void *value = g_hash_table_lookup(dict, key);
    struct MyStruct *obj;
    if (!value) {
        obj = (struct MyStruct *)value;
    } else {
        compute_obj
        g_hash_table_insert(dict, key, obj);
    }
    do_something_with_obj
}

with #pragma omp parallel for, or I need to use some other OpenMP pragmas? At times I got an error in that loop. One thread version works fine.

Hristo Iliev
  • 72,659
  • 12
  • 135
  • 186
aptypr
  • 417
  • 5
  • 15
  • 1
    You should surround all calls to `g_hash_table_*` from inside the parallel region with `#pragma omp critical { ... }` (the curly braces go on the next line). – Hristo Iliev Oct 08 '12 at 09:49

1 Answers1

1

No. From the Threads section of the GLib Reference Manual:

GLib itself is internally completely thread-safe (all global data is automatically locked), but individual data structure instances are not automatically locked for performance reasons. For example, you must coordinate accesses to the same GHashTable from multiple threads. The two notable exceptions from this rule are GMainLoop and GAsyncQueue, which are thread-safe and need no further application-level locking to be accessed from multiple threads. Most refcounting functions such as g_object_ref() are also thread-safe.

nemequ
  • 16,623
  • 1
  • 43
  • 62
  • _For example, you must coordinate accesses to the same GHashTable from multiple threads._ Doesn't this mean that I have to use pragmas to work with GHashTable? – aptypr Oct 08 '12 at 03:48
  • The original question was "Are g_hash_table_lookup and g_hash_table_insert thread-safe?", and the answer is "No." If you can use OpenMP pragmas to restrict access to a single thread then that would be an option. You could also use something like GMutex. – nemequ Oct 08 '12 at 09:20