您的位置:首页 > 运维架构 > Linux

Linux 条件变量的使用pthread_cond

2017-02-18 17:40 1426 查看
使用单个条件变量时,必须cond_wait首先达到wait状态  用sleep

/******************************************************
/*: Object detection algrithm running in Linux
/*: Update: Naive version(线程实现简单的生产者消费者模式)
/*: 1:Vehicle algrithm
/******************************************************/

#include <iostream>
#include <vector>
#include <queue>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include "Network.h"
#include "VehicleAlgrithm.h"
//#include "global.h"

#define MAX_TASKS 10
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int iStatus = 0;

void* producer(void *ptr)
{
int iNum;
while(true)
{
std::cout<<"produce...."<<std::endl;
Server* ps = Server::GetInstance();
ps->ReceiveCommand();
pthread_mutex_lock(&the_mutex);
//while(iStatus !=0) pthread_cond_wait(&condp, &the_mutex);
iStatus++;
std::cout<<iStatus<<":task Added..."<<std::endl;
pthread_cond_signal(&condc);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}

void* consumer(void *ptr)
{
int iNum;
std::cout<<"TEST Process Task..."<<std::endl;
std::string VideoPath("");
//VehicleAlgrithm* vehicleAlg = VehicleAlgrithm::GetAlgInstance();
std::cout<<"Create a vehicleAlg instance."<<std::endl;
while(true)
{
std::cout<<"waitting the Task !"<<std::endl;
pthread_mutex_lock(&the_mutex);
while(iStatus == 0) pthread_cond_wait(&condc, &the_mutex);
//Get a task from the queue
//vehicleAlg->ProcessTask(VideoPath);
iStatus--;
std::cout<<iStatus<<":task reduce..."<<std::endl;
std::cout<<"Start Vehicle process video task ... :"<<VideoPath<<std::endl;
//Transfer the result.txt to client...
//pthread_cond_signal(&condp);
pthread_mutex_unlock(&the_mutex);
sleep(2);
std::cout<<"Video Task done !"<<std::endl;
std::cout<<"Transfer the result.txt to client..."<<std::endl;
}
pthread_exit(0);
}

int main(int argc, char *argv[])
{
io_service ios;
Server serv(ios);

//Server* pS = Server::GetInstance();
//std::cout<<"test read cmd !..."<<std::endl;
//pS->ReceiveCommand();
//std::cout<<"test read cmd done!"<<std::endl;

pthread_t pro, con;
pthread_mutex_init(&the_mutex, 0);
pthread_cond_init(&condc,0);
//pthread_cond_init(&condp,0);
pthread_create(&con, 0, consumer, 0);
sleep(2);
pthread_create(&pro, 0, producer, 0);

pthread_join(pro,0);
pthread_join(con,0);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
pthread_mutex_destroy(&the_mutex);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: