Thread: help with pthread_mutex_t

  1. #1
    Registered User
    Join Date
    Dec 2006

    help with pthread_mutex_t

    Right, Ive got a 2D array of cells mycell[5][5] and each runs upon its own thread.

    In this thread each cell it to have its own mutex and variable condition.

    I think I am getting a segmentation fault because I have been creating each mutex by

     pthread_mutex_t mutex[r][c]
    where r and c are the row and column of the 2D array.

    So the above code is simply a way of trying to index the mutex belonging to each cell's thread.

    But I now think that when, for example, r = 3 and c = 2, the above code creates a 2D array of mutexes [3][2] instead of a single mutex belonging to mycell[3][2].

    This is where I need some help please! My runner code for each thread is aware of the r and c values so it knows which cell it should be creating a mutex for, but I have no idea how to create a mutex that is indexed to that cell.

    Any help would be greatly appreciated. Thanks.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Why not have
    struct foo {
        int var;
        pthread_mutex_t mutex;
    } mycell[5][5];
    Each thread is invoked with a pointer to a cell - &mycell[r][c]

    Each thread function casts the void * to a struct foo *ptr

    Then uses ptr->var and ptr->mutex as appropriate.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed