c++ 多线程 队列 顺序取出数据

c++ 多线程 队列 顺序取出数据,第1张

菜鸟实现耗时测试,勿喷

#include <iostream>

#include <queue>

#include <thread>

#include <mutex>

#include <unistd.h>

#include <semaphore.h>

using namespace std

#define msleep(x) usleep(x*1000)

queue<int>queueIn

queue<int>queueOut

std::mutex threadMutex

int max_len = 4

int index = 0

static sem_t g_semaphore

static sem_t g_semaphore_queuOut

bool isEnd = false

void decoder() {

    int i = 0

    while (i <10000) {

        if(queueIn.size() >max_len) {

            continue

        }

        queueIn.push(i++)

    }

    while (index != 9999) {

    }

    isEnd = true

}

void encoder() {

    int i = -1

    while (!isEnd || !queueIn.empty()) {

        i = -1

        sem_wait(&g_semaphore)

        if(!queueIn.empty()){

            i = queueIn.front()

            queueIn.pop()

        }

        sem_post(&g_semaphore)

        if(i == -1){

            continue

        }

        while (true){

            if(i == 0){

                break

            }

            //printf("index %d i %d\n",index,i)

            if(i - index == 1){

                break

            }

        }

        sem_wait(&g_semaphore_queuOut)

        queueOut.push(i)

        if(i >index) {

            index = i

        }

        sem_post(&g_semaphore_queuOut)

    }

}

void enCoderH264() {

    while (!isEnd || !queueOut.empty() || !queueIn.empty()) {

        sem_wait(&g_semaphore_queuOut)

        if(!queueOut.empty()){

            int i = queueOut.front()

            queueOut.pop()

            printf("queueout %d \n",i)

        }

        sem_post(&g_semaphore_queuOut)

    }

    //printf("end %d \n",queueOut.size())

}

int main() {

    sem_init(&g_semaphore, 0, 1)

    sem_init(&g_semaphore_queuOut,0,1)

    thread t(decoder)

    thread t2(encoder)

    thread t3(encoder)

    thread t4(encoder)

    thread t5(enCoderH264)

    t.detach()

    t2.detach()

    t3.detach()

    t4.detach()

    t5.detach()

    std::cout <<"Hello, World!" <<std::endl

    pthread_exit(NULL)

    return 0

}

给ArrayBlockingQueue加把锁,

如果需要读取它的资源,需要首先拿到这把‘锁’,拿到资源后再放开锁;

所有线程都需要首先拿锁;

这样做可避免你说的问题.

补充:

这可能是take *** 作的问题,查查msdn,take *** 作会在取到数据后把数据从ArrayBlockingQueue删掉吗?如果不会,那么你需要手动加入code把该数据删掉,删除 *** 作要在解锁前做。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/sjk/6668410.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-26
下一篇 2023-03-26

发表评论

登录后才能评论

评论列表(0条)

保存