Thread: locking/threads hash table

  1. #1
    Registered User
    Join Date
    Nov 2009
    Posts
    7

    locking/threads hash table

    Hello,

    Im relatively knew to programming and any help is appreciated. My question is this...

    I am creating a library that implements a thread-safe hash table.
    I am curious how to initialize a lock for each "bucket" of the hash table.
    here is the code I have for the initializing part only....
    Code:
    void Hash_Init(int buckets)
    {
        int i = 0;
    
        hash_buckets = malloc(buckets * sizeof(struct hash_bucket));
        g_numOfBuckets = buckets;
        
        for (i = 0; i < buckets; i++) {
    	hash_buckets[i].head = NULL;
        }
    }

  2. #2
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    You could add a mutex to your hash_bucket struct, and lock/unlock it whenever you manipulate a bucket.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  3. #3
    Registered User
    Join Date
    Nov 2009
    Posts
    7
    okay want to make sure I understand exactly what you are saying...

    new code with structure updates

    Code:
    //added structure
    struct hash_bucket
    {
        struct hash_element *head; //pointer to each element in the bucket
        pthread_mutex_t mutex;
    };
    void Hash_Init(int buckets)
    {
        int i = 0;
    
        hash_buckets = malloc(buckets * sizeof(struct hash_bucket));
        g_numOfBuckets = buckets;
        
        for (i = 0; i < buckets; i++) {
    	hash_buckets[i].head = NULL;
    	hash_buckets[i].mutex = PTHREAD_MUTEX_INITIALIZER;  //added
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dictionary in C# to hash table in C?
    By dinoman in forum C Programming
    Replies: 2
    Last Post: 04-12-2009, 09:23 PM
  2. Writing array, to file
    By zootreeves in forum C Programming
    Replies: 9
    Last Post: 09-08-2007, 05:06 PM
  3. Group Project Help/Volunteer
    By DarkDot in forum C++ Programming
    Replies: 3
    Last Post: 04-24-2007, 11:36 PM
  4. Hash table creation and insertion
    By tgshah in forum C Programming
    Replies: 1
    Last Post: 01-23-2006, 07:54 PM
  5. Not sure on hash table memory allocations
    By Thumper333 in forum C Programming
    Replies: 3
    Last Post: 09-27-2004, 09:00 PM