File: skiplist.c

package info (click to toggle)
clearsilver 0.10.5-7
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,304 kB
  • sloc: ansic: 24,586; python: 4,233; sh: 2,502; cs: 1,429; ruby: 819; java: 735; makefile: 589; perl: 120; lisp: 34; sql: 21
file content (632 lines) | stat: -rw-r--r-- 16,159 bytes parent folder | download | duplicates (10)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
/* 
 *
 * Thread-safe Skiplist Using Integer Identifiers
 * Copyright 1998-2000 Scott Shambarger (scott@shambarger.net)
 *
 * This software is open source. Permission to use, copy, modify, and
 * distribute this software for any purpose and without fee is hereby granted,
 * provided that the above copyright notice appear in all copies.  No
 * warranty of any kind is expressed or implied.  Use at your own risk.
 *
 * 1/14/2001 blong
 *   Made it use neo errs... probably need to check locking functions
 *   for error returns...
 *
 */

#include "cs_config.h"

#include <stdlib.h>
#include <assert.h>
#include <string.h>

#include "neo_misc.h"
#include "neo_err.h"
#include "skiplist.h"
#include "ulocks.h"

typedef struct skipItem *skipItem;

/* structure is sized on allocation based on its level */
struct skipItem {
  UINT32 locks;                                   /* count of locks on value */
  UINT32 key;                                                  /* item's key */
  void *value;                                               /* item's value */
  INT32 level;                                                 /* item level */
  skipItem next[1];                                   /* array of next items */
};

#define SIZEOFITEM(max) (sizeof(struct skipItem) + \
                         ((max+1) * sizeof(skipItem)))

struct skipList_struct {
  INT32 topLevel;                           /* current max level in any item */
  INT32 levelHint;                          /* hint at level to start search */
  skipItem header;                           /* header item (has all levels) */
  skipItem tail;                               /* tail item (has all levels) */

  /* elements to handle cached deleted items */
  skipItem deleted; /* cached deleted items (linked by level+1 next entries) */
  UINT32 cached;                            /* number of cached deleted items */

  int flushing;             /* TRUE if thread waiting to flush cached items */
  UINT32 readers;                                /* number of current readers */
  int block;                                 /* TRUE if readers should wait */

  pthread_mutex_t read;                     /* readers count/cond wait mutex */
  pthread_mutex_t write;                                     /* writer mutex */
  pthread_cond_t resume;             /* condition to wait on to resume reads */
  pthread_cond_t flush;                    /* condition to wait on for flush */

  /* list constants */
  int threaded;                     /* TRUE if list needs to be thread safe */
  UINT32 flushLimit;      /* max number of cached deleted items before flush */
  INT32 maxLevel;                                /* max level list can reach */
  double randLimit;                       /* min random value to jump levels */
  skipFreeValue freeValue;                            /* free value callback */
  void *freeValueCtx;             /* context to pass to <freeValue> callback */
};

static void readLock(skipList list) {

  mLock(&list->read);

  if(list->block)
    cWait(&list->resume, &list->read);

  list->readers++;

  mUnlock(&list->read);

  return;
}

static void readUnlock(skipList list, skipItem x, void **plock) {

  int startFlush = FALSE;

  if(list->threaded)
    mLock(&list->read);

  if(plock) {
    x->locks++;
    *plock = x;
  }

  if(! list->threaded)
    return;

  list->readers--;

  if((list->readers == 0) && list->block)
    startFlush = TRUE;

  mUnlock(&list->read);

  if(startFlush)
    cSignal(&list->flush);

  return;
}

static void readBlock(skipList list) {

  mLock(&list->read);

  list->block = TRUE;

  if(list->readers)
    cWait(&list->flush, &list->read);    /* wait until reader locks released */

  return;
}

static void readUnblock(skipList list) {

  list->block = FALSE;

  mUnlock(&list->read);

  cBroadcast(&list->resume);

  return;
}


static void writeLock(skipList list) {

  mLock(&list->write);

  return;
}

static void writeUnlock(skipList list) {

  mUnlock(&list->write);

  return;
}

static NEOERR *skipAllocItem(skipItem *item, UINT32 level, UINT32 key, 
    void *value) 
{

  if(! (*item = malloc(SIZEOFITEM(level))))
    return nerr_raise(NERR_NOMEM, "Unable to allocate space for skipItem");

  /* init new item */
  (*item)->locks = 0;
  (*item)->key = key;
  (*item)->value = value;
  (*item)->level = level;

  return STATUS_OK;
}

static void skipFreeItem(skipList list, skipItem item) {

  if(list->freeValue)
    list->freeValue(item->value, list->freeValueCtx);          /* free value */

  free(item);                                                /* release item */

  return;
}

static void skipFlushDeleted(skipList list, int force) {

  skipItem x, y, next;

  x = list->deleted;
  y = x->next[x->level + 1];

  while(y != list->tail) {

    next = y->next[y->level + 1];

    if(force || (! y->locks)) {           /* check if value currently locked */

      x->next[x->level + 1] = next;         /* set previous item's next link */
      skipFreeItem(list, y);                                    /* free item */

      list->cached--;                                 /* update cached count */
    }
    else {
      x = y;                             /* make this item the previous item */
    }

    y = next;                                        /* advance to next item */
  }
  
  return;
}

static void skipWriteUnlock(skipList list) {

  int flush;

  if(! list->threaded)
    return;

  if((list->cached > list->flushLimit) && (! list->flushing)) {
    list->flushing = TRUE;
    flush = TRUE;
  }
  else {
    flush = FALSE;
  }

  writeUnlock(list);                      /* let any pending writes complete */
  readUnlock(list, NULL, NULL);                         /* no longer reading */

  if(flush) {
                                        /* we are now flushing deleted items */

    readBlock(list);                               /* acquire all read locks */

                              /* at this point no readers/writers are active */

    skipFlushDeleted(list, FALSE);                    /* flush deleted items */

    list->flushing = FALSE;                                 /* done flushing */

    readUnblock(list);                              /* let everyone continue */
  }

  return;
}

static skipItem skipFind(skipList list, UINT32 key) {

  skipItem x, y = NULL;
  INT32 i;

  if(list->threaded)
    readLock(list);

  x = list->header;                            /* header contains all levels */

  for(i = list->levelHint;      /* loop from levelHint level down to level 0 */
      i >= 0;
      i--) {

    y = x->next[i];                            /* get next item at new level */

    while(y->key < key) {       /* if y has a smaller key, try the next item */
      x = y;                                  /* save x in case we overshoot */
      y = x->next[i];                                       /* get next item */
    }
  }

  return y;
}

void *skipSearch(skipList list, UINT32 key, void **plock) {

  skipItem y;
  void *value;

  y = skipFind(list, key);                                      /* find item */

  if(y->key == key) {                     /* y has our key, or it isn't here */
    value = y->value;
  }
  else {                              /* didn't find item, don't allow locks */
    value = NULL;
    plock = NULL;
  }

  readUnlock(list, y, plock);

  return value;
}

void *skipNext(skipList list, UINT32 *pkey, void **plock) {

  skipItem y;
  void *value;

  y = skipFind(list, *pkey);                                    /* find item */

  if((y->key == *pkey) && (y != list->tail))      /* skip to next if found y */
    y = y->next[0];

  if(y != list->tail) {                   /* reset key to next, return value */
    *pkey = y->key;
    value = y->value;
  }
  else {                                  /* no next item, don't allow locks */
    value = NULL;
    plock = NULL;
  }

  readUnlock(list, y, plock);

  return value;
}

void skipRelease(skipList list, void *lock) {

  skipItem x;

  mLock(&list->read);

  x = lock;
  x->locks--;

  mUnlock(&list->read);

  return;
}

/* list is write locked */
static NEOERR *skipNewItem(skipList list, skipItem *item, UINT32 key, 
    void *value) 
{

  INT32 level = 0;

  while((drand48() < list->randLimit) && (level < list->maxLevel))
    level++;

  if(level > list->topLevel) {

    if(list->topLevel < list->maxLevel)
      list->topLevel++;

    level = list->topLevel;
  }

  return skipAllocItem(item, level, key, value);
}

/* list is write locked */
static void skipDeleteItem(skipList list, skipItem item) {

  if(list->threaded) {
    item->next[item->level + 1] = list->deleted->next[1];
    list->cached++;
    list->deleted->next[1] = item;
  }
  else {
    skipFreeItem(list, item);
  }

  return;
}

NEOERR *skipNewList(skipList *skip, int threaded, int root, int maxLevel,
                     int flushLimit, skipFreeValue freeValue, void *ctx) 
{
  NEOERR *err;
  skipList list;
  UINT32 i;

  *skip = NULL;
  if(! (list = calloc(1, sizeof(struct skipList_struct))))
    return nerr_raise(NERR_NOMEM, "Unable to allocate memore for skiplist");

  if (maxLevel == 0)
    return nerr_raise(NERR_ASSERT, "maxLevel must be greater than 0");

  if(maxLevel >= SKIP_MAXLEVEL)                              /* check limits */
    maxLevel = SKIP_MAXLEVEL-1;

  if(root > 4)
    root = 4;
  else if(root < 2)
    root = 2;

  list->maxLevel = maxLevel;                          /* init list constants */
  list->randLimit = 1.0 / (double)root;
  list->threaded = threaded;
  list->freeValue = freeValue;
  list->freeValueCtx = ctx;

  do {
    if(threaded) {

      list->flushLimit = flushLimit;

      err = mCreate(&list->read);
      if (err != STATUS_OK) break;

      err = mCreate(&list->write);
      if (err != STATUS_OK) break;

      err = cCreate(&list->resume);
      if (err != STATUS_OK) break;

      err = cCreate(&list->flush);
      if (err != STATUS_OK) break;
    }

    err = skipAllocItem(&(list->header), list->maxLevel, 0, NULL);
    if (err != STATUS_OK) break;
    err = skipAllocItem(&(list->tail), list->maxLevel, (UINT32)-1, NULL);
    if (err != STATUS_OK) break;
    err = skipAllocItem(&(list->deleted), 0, 0, NULL);
    if (err != STATUS_OK) break;

    for(i = 0;                                       /* init header and tail */
        i <= list->maxLevel;
        i++) {
      list->tail->next[i] = NULL;
      list->header->next[i] = list->tail;
    }

    list->deleted->next[1] = list->tail;

    *skip = list;
    return STATUS_OK;                                     /* return new list */

  } while(FALSE);

  if(list->header)                              /* failed to make list, bail */
    free(list->header);
  free(list);

  return nerr_pass(err);
}

/* list considered locked */
static void skipFreeAllItems(skipList list) {

  UINT32 i;
  skipItem x, y;

  x = list->header->next[0];

  while(x != list->tail) {
    y = x->next[0];                    /* get next item from level 0 pointer */
    skipFreeItem(list, x);                                   /* release item */
    x = y;
  }
                                                    /* clear header pointers */
  for(i = 0;
      i <= list->maxLevel;
      i++)
    list->header->next[i] = list->tail;

  return;
}

void skipFreeList(skipList list) {

  skipFlushDeleted(list, TRUE);                       /* flush deleted items */

  skipFreeAllItems(list);                                 /* free list items */
  
  if(list->threaded) {
    cDestroy(&list->flush);
    cDestroy(&list->resume);
    mDestroy(&list->write);
    mDestroy(&list->read);
  }

  free(list->tail);                                             /* free list */
  free(list->header);
  free(list->deleted);
  free(list);

  return;
}

/* <list> is locked, <x> is at least level <level>, and <x>->key < <key> */
static skipItem skipClosest(skipItem x, UINT32 key, UINT32 level) {

  skipItem y;

  y = x->next[level];                         /* get next item at this level */
  
  while(y->key < key) {       /* ensure that we have the item before the key */
    x = y;
    y = x->next[level];
  }

  return x;
}

static skipItem skipLock(skipList list, UINT32 key, skipItem *save, INT32 top) {

  INT32 i;
  skipItem x, y;

  if(list->threaded)
    readLock(list);

  x = list->header;                            /* header contains all levels */

  for(i = top;                        /* loop from top level down to level 0 */
      i >= 0;
      i--) {

    y = x->next[i];                           /* get next item at this level */

    while(y->key < key) {       /* if y has a smaller key, try the next item */
      x = y;                                  /* save x in case we overshoot */
      y = x->next[i];                                       /* get next item */
    }

    save[i] = x;                  /* preserve item with next pointer in save */
  }

  if(list->threaded)
    writeLock(list);                                 /* lock list for update */

                               /* validate we have the closest previous item */
  return skipClosest(x, key, 0);
}

NEOERR *skipInsert(skipList list, UINT32 key, void *value, int allowUpdate) 
{
  NEOERR *err;
  INT32 i, level;
  skipItem save[SKIP_MAXLEVEL];
  skipItem x, y;

  if (value == 0)
    return nerr_raise(NERR_ASSERT, "value must be non-zero");
  if (key == 0 || key == (UINT32)-1)
    return nerr_raise(NERR_ASSERT, "key must not be 0 or -1");

  level = list->levelHint;

  x = skipLock(list, key, save, level);              /* quick search for key */

  y = x->next[0];

  if(y->key == key) {

    if(!allowUpdate)
    {
      skipWriteUnlock(list);
      return nerr_raise(NERR_DUPLICATE, "key %u exists in skiplist", key);
    }

    y->value = value;                       /* found the key, update value */
    skipWriteUnlock(list);
    return STATUS_OK;
  }

  err = skipNewItem(list, &y, key, value);
  if (err != STATUS_OK)
  {
    skipWriteUnlock(list);
    return nerr_pass(err);
  }

  for(i = level + 1;             /* is new item has more levels than <level> */
      i <= y->level;                                   /* if so fill in save */
      i++)
    save[i] = list->header;

  for(i = 0;                             /* populate pointers for all levels */
      i <= y->level;
      i++) {
    
    if(i)                       /* check that save is correct for each level */
      x = skipClosest(save[i], key, i);

    y->next[i] = x->next[i];            /* now insert the item at this level */
    x->next[i] = y;            /* (order here important for thread-safeness) */
  }

  while((list->levelHint < list->topLevel)               /* update levelHint */
        && (list->header->next[list->levelHint+1] != list->tail)) 
    list->levelHint++;

  skipWriteUnlock(list);

  return STATUS_OK;
}

void skipDelete(skipList list, UINT32 key) {

  INT32 i, level;
  skipItem save[SKIP_MAXLEVEL];
  skipItem x, y;

  assert(key && (key != (UINT32)-1));

  level = list->levelHint;

  x = skipLock(list, key, save, level);              /* quick search for key */

  y = x->next[0];

                        /* check that we found the key, and it isn't deleted */
  if((y->key != key) || (y->next[0]->key < key)) {
    skipWriteUnlock(list);
    return;
  }

  for(i = level + 1;           /* check if item has more levels than <level> */
      i <= y->level;                                   /* if so fill in save */
      i++)
    save[i] = list->header;

  for(i = y->level;
      i >= 0;
      i--) {

                                /* check that save is correct for each level */
    x = skipClosest(save[i], key, i);

    x->next[i] = y->next[i];                /* now remove item at this level */
    y->next[i] = x;          /* (order here is imported for thread-safeness) */
  }

  skipDeleteItem(list, y);                            /* put on deleted list */

  while((list->levelHint > 0)                            /* update levelHint */
        && (list->header->next[list->levelHint] == list->tail))
    list->levelHint--;

  skipWriteUnlock(list);

  return;
}