Skip to content

Commit

Permalink
if the table is being grown we need to wait for it to finish
Browse files Browse the repository at this point in the history
if a thread is accessing a list from the previous items array and later locking the list
is not safe because there is a race and the list (or the old items array) might be released
by the thread growing the table before the list is being locked by the initial thread
  • Loading branch information
xant committed Jun 12, 2014
1 parent 43a756d commit dd2f182
Showing 1 changed file with 4 additions and 8 deletions.
12 changes: 4 additions & 8 deletions src/hashtable.c
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ static inline ht_items_list_t *
ht_get_list_at_index(hashtable_t *table, uint32_t index)
{
ht_items_list_t *list = NULL;
if (ATOMIC_READ(table->growing) > index) {
if (ATOMIC_READ(table->growing)) {
MUTEX_LOCK(table->lock);
list = ATOMIC_READ(table->items[index]);
MUTEX_UNLOCK(table->lock);
Expand Down Expand Up @@ -213,16 +213,12 @@ ht_grow_table(hashtable_t *table)
if (table->max_size && new_size > table->max_size)
new_size = table->max_size;

//fprintf(stderr, "Growing table from %u to %u\n", __sync_fetch_and_add(&table->size, 0), new_size);
//fprintf(stderr, "Growing table from %u to %u\n",
// __sync_fetch_and_add(&table->size, 0), new_size);

ht_items_list_t **items_list =
(ht_items_list_t **)calloc(new_size, sizeof(ht_items_list_t *));

if (!items_list) {
//fprintf(stderr, "Can't create new items array list: %s\n", strerror(errno));
return;
}

ht_item_t *item = NULL;

for (i = 0; i < ATOMIC_READ(table->size); i++) {
Expand Down Expand Up @@ -393,7 +389,7 @@ ht_set_internal(hashtable_t *table,
uint32_t current_size = ATOMIC_READ(table->size);
if (ht_count(table) > (current_size + (current_size/3)) &&
(!table->max_size || current_size < table->max_size) &&
!ATOMIC_READ(table->growing))
ATOMIC_CAS(table->growing, 0, 1))
{
ht_grow_table(table);
}
Expand Down

0 comments on commit dd2f182

Please sign in to comment.