0

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.

Suresh Kumar
  • 1,077
  • 1
  • 12
  • 21

2 Answers2

1

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.

Germann Arlington
  • 3,315
  • 2
  • 17
  • 19
0

You need to use a mutex (mutual exclusion) variable. The pthread library has everything you will need. Here's a good place to start looking at the available functions:

http://pubs.opengroup.org/onlinepubs/009695399/basedefs/pthread.h.html

You'll need to init a mutex variable that each thread will have access to: http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_mutex_init.html

Then your threads will need to lock it when they need access to shared memory, and then unlock it when they are done using the shared memory: http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_mutex_lock.html

Here's a simple example: http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=%2Frzahw%2Frzahwe18rx.htm

Good luck!

Joey
  • 464
  • 2
  • 9