开发者

Behaviour of an hashtable using glib

开发者 https://www.devze.com 2023-03-09 02:06 出处:网络
I want to update the Volume to each @IP. So that for example after each 5 s I add V(i) of each @IP(i). Ok Now the hash table works fine it keeps updated after every T seconds. But the problem is that

I want to update the Volume to each @IP. So that for example after each 5 s I add V(i) of each @IP(i). Ok Now the hash table works fine it keeps updated after every T seconds. But the problem is that after a certain period I find that sometimes the same ip adress is repeated twice or even a lot of times within the hash table. So that when I close the process I find the same @IP repeated too many times. It is like there is a problem with the hash table or something like that.

Here is the code this funcion "update_hashTable()" is so important it is called every X seconds I suspect in fact a memory leak ... because I always call malloc for IP@. but it keeps working ... any idea ???

int update_hashTable( ... ) {

u_int32_t *a;

... //declarations

struct pf_addr *as;


as = ks->addr[0];

a = (u_int32_t*)malloc(sizeof(u_int32_t));

*a = ntohl(as->addr32[0]);

sz = value; // no matter it is... an int for example

if (ReturnValue=(u_int32_t)g_hash_table_lookup(hashtable, a)) {

  ReturnValue +=sz;
  g_hash_table_insert(hashtable, (gpointer)a, gpointer)ReturnValue);
}
else {
  g_hash_table_in开发者_JAVA百科sert(hashtable, (gpointer)a, (gpointer)sz);
}


Indeed, you appear to have a memory leak, but this isn't your problem. The problem is that the true-path of your if statement simply reinserts a second value associated with the same key, which is not what you want.

The typical pattern for this check-if-exists and increment algorithm is usually something like

gpointer val = g_hash_table_lookup(hash_table, key);
if (val == NULL) {
    val = g_malloc0(...);
    g_hash_table_insert(hash_table, key, val);
}
*val = /* something */;

The important thing to take away from this is that once you have a pointer to the value associated with some key, you can simply modify it directly.

If this code will be executed by multiple threads in parallel, then the entire block should be protected by a mutex, perhaps with GMutex: http://developer.gnome.org/glib/2.28/glib-Threads.html

gcc provides atomic builtin intrinsics, say for atomically incrementing the value, see http://gcc.gnu.org/onlinedocs/gcc/Atomic-Builtins.html

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号