Home > Software engineering >  Where is my error decrementing the semaphor?
Where is my error decrementing the semaphor?

Time:09-24

I'm using semaphors. I have two threads. The first thread, every two seconds, executes a loop that creates a dynamic array. At the beginning of the loop it creates the dynamic array, and eventually deletes it. On the other hand, a thread must write to this dynamic array, obviously provided that it has already been created and that it has not yet been deleted (i.e., after creation and before deletion). I don't know how to use correctly semaphores. Where am I doing wrong? Thank you for your help!

int *array
int position = 0;
static void *thread_A(void *p_vp_arg)
{

    while (1)
    {
        sem_post(&sem);
        array = malloc(1024*sizeof(int));
        /* SOME STUFF HERE */
        sleep(2);
        free(array);
    }
}

static void function_B(...){
    if(sem_trywait(&sem)){
        printf("I can write into the array\n");
        array[position] = variable;
        position  = 1;
    }
}

Into the main:

sem_init(&sem, 0, 0)

CodePudding user response:

In your deceleration of the array you perform sem_post() before you allocate the array this should really be after it, with a sem_wait() before the deletion as right now you are releasing the lock and allowing the other thread to try access it before it has been malloced. and you could also delete it while another thread is currently writing to the array.

In the writing method i would switch to using sem_wait instead of sem_trywait it will then handle most of the waiting itself. this is unless you have a specific reason to use sem_trywait

Also don't use the sem result from sem_trywait() or any sem as a loop condition this can cause it to fail. instead do

int result = sem_trywait(&sem)
if(result == 0){
    //rest of code

it returns 0 on success and or an errorcode for anything else more can be read on the manual page about the specific errors

Finally you never release the lock in the writing thread, you need to do sem_post() when you are done with the lock as right now you never release the lock.

  • Related