Search code examples
cpthreadsfifothread-synchronization

suspend execution of other function in a multithreaded application


I am implementing FIFO in C. One thread is writing in FIFO and other is reading from it.

#define BUFFER_LENGTH   1000
struct Frame
{
    char data[1024];
    unsigned int data_len;
    struct Frame* frame;
};

struct Frame * get_from_fifo ()
{
    if (!fifo_length)
    {
        first = last = NULL;
        return NULL;
    }
    struct Frame* frame = first;
    first = first->frame;
    fifo_length--;
    return frame;
}


int add_to_fifo (const char* data, unsigned int frame_size)
{
    if (fifo_length >= BUFFER_LENGTH)
    {
        ast_log(LOG_ERROR, "Buffer full\n");
        return SURESH_ERROR;
    }

    struct Frame* frame = malloc(sizeof (struct Frame));
    frame->data_len = frame_size;
    memcpy(frame->data, data, frame_size);

    if (last)
    {
        last->frame = frame;
        last = frame;
    }

    if (!first)
    {
        first = last = frame;
    }
    fifo_length++;
    return SURESH_SUCCESS;
}

how can I prevent functions *add_to_fifo* and *get_from_fifo* to be called at the same time by different threads. i.e. *get_from_fifo* should only be called when the other thread is not executing *add_to_fifo* and vice verca.


Solution

  • As you are implementing FIFO stack the only really concurrent operation you have is changing the stack size (fifo_length).
    You are adding entries to the tail of the stack and removing entries from the head of the stack so these two operation will never interfere with each other. So the only part you will need to worry about is changing the stack size (fifo_length), I would put it into separate function synchronised by mutex or flag (as mentioned by "Joey" above) and call it from both add_to_fifo() and get_from_fifo() functions.