Linux 条件变量的使用pthread_cond

本文介绍了一个基于Linux环境的车辆检测算法,通过线程实现简单的生产者消费者模式来处理视频任务。利用条件变量和互斥锁进行线程同步,确保任务的生产和消费有序进行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用单个条件变量时,必须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;    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值