g_hash_table_lookup
和 g_hash_table_insert
是线程安全的吗?我可以使用这样的代码吗:
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
}
使用 #pragma omp parallel for
,或者我需要使用其他一些 OpenMP 编译指示?
有时我在那个循环中遇到错误。一个线程版本工作正常。
最佳答案
没有。来自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.
关于c++ - g_hash_table 和 OpenMp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12771591/