菜鸟实现耗时测试,勿喷
#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;
}
网友评论