【问题标题】:suspend execution of other function in a multithreaded application在多线程应用程序中暂停执行其他功能
【发布时间】:2012-09-02 20:11:18
【问题描述】:

我正在用 C 实现 FIFO。一个线程正在写入 FIFO,另一个正在读取它。

#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;
}

如何防止函数 *add_to_fifo* 和 *get_from_fifo* 被不同的线程同时调用。即 *get_from_fifo* 只应在其他线程未执行 *add_to_fifo* 时调用,反之亦然。

【问题讨论】:

    标签: c pthreads fifo thread-synchronization


    【解决方案1】:

    当您实现 FIFO 堆栈时,只有真正的并发操作正在更改堆栈大小 (fifo_length)。
    您正在将条目添加到堆栈的尾部并从堆栈的头部删除条目,因此这两个操作永远不会相互干扰。因此,您需要担心的唯一部分是更改堆栈大小(fifo_length),我会将其放入由互斥锁或标志同步的单独函数中(如上面的“Joey”所述)并从两者中调用它add_to_fifo()get_from_fifo() 函数。

    【讨论】:

      【解决方案2】:

      您需要使用互斥(互斥)变量。 pthread 库拥有您需要的一切。这是开始查看可用功能的好地方:

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

      您需要初始化每个线程都可以访问的互斥变量: http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_mutex_init.html

      然后您的线程需要在需要访问共享内存时锁定它,然后在使用完共享内存后解锁它: http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_mutex_lock.html

      这是一个简单的例子: http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=%2Frzahw%2Frzahwe18rx.htm

      祝你好运!

      【讨论】:

        猜你喜欢
        • 2016-03-21
        • 1970-01-01
        • 1970-01-01
        • 2021-09-12
        • 1970-01-01
        • 1970-01-01
        • 2019-10-03
        • 2018-05-02
        • 2015-03-05
        相关资源
        最近更新 更多