技术

多线程队列

2017-10-20  本文已影响0人  flycloud_hz

0x0 队列在多线程中的应用
消息产生及消费一般在不同的线程,多线程需互斥访问队列。

0x1 代码实现
一个队列负责消息push/pop,多个线程产生/消费。

变量定义

bool g_running = false;
std::queue<std::string> g_queue;
pthread_t g_id;
pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t g_cond = PTHREAD_COND_INITIALIZER;

线程从队列读取消息,进行处理;队列为空则等待。

while (g_running) {
    std::string msg;
    if (g_queue.empty()) {
        pthread_mutex_lock(&g_mutex);
        pthread_cond_wait(&g_cond, &g_mutex);
        if (g_running && !g_queue.empty()) {
            msg = g_queue.front();
            g_queue.pop();
        }
        pthread_mutex_unlock(&g_mutex);
    } else {
        pthread_mutex_lock(&g_mutex);
        if (g_running && !g_queue.empty()) {
            msg = g_queue.front();
            g_queue.pop();
        }
        pthread_mutex_unlock(&g_mutex);
    }

    if (g_running && !msg.empty()) {
        LOGE("msg %s", msg.c_str());
        // process msg

    }
}

消息插入队列

std::string msg;
if (g_running) {
    pthread_mutex_lock(&g_mutex);
    g_queue.push(std::string(msg));
    pthread_cond_signal(&g_cond);
    pthread_mutex_unlock(&g_mutex);
}

等待处理消息的线程退出

if (g_running) {
    g_running = false;
    pthread_mutex_lock(&g_mutex);
    pthread_cond_signal(&g_cond);
    pthread_mutex_unlock(&g_mutex);
    pthread_join(g_id, NULL);
}

0x2 如何提高性能
每次从队列取一个消息,都会调用锁,导致性能比较低下;更好的是调用队列swap函数,一个接收消息的队列,一个处理消息的队列,将接收消息队列的所有消息一次性传给处理消息的队列;这样会减少锁的调用次数,性能大幅提高。

上一篇下一篇

猜你喜欢

热点阅读