gpt4 book ai didi

c - 使用 select() 调用文件 I/O 的 Pthread 生产者/消费者

转载 作者:太空宇宙 更新时间:2023-11-03 21:54:12 29 4
gpt4 key购买 nike

我正在尝试提高我正在开发的实时计算机视觉程序的捕获性能,该程序使用 OpenCV 在嵌入式 Linux 计算机上运行。我想使用多个线程和一个共享内存缓冲区来分离 (1) 捕获视频帧和 (2) 处理它们的任务(我相信是“生产者/消费者问题”)。我已经阅读了 pthreads、mutex 变量和条件变量,但不明白如何将它们与 select() 函数一起使用。

现在,视频帧是使用改编自 Video4Linux2 Video Capture Example 的代码捕获的它使用了 select()。据我了解,select() 会阻止程序,直到网络摄像头提供数据为止,这可能很慢并且会浪费大量时间。如果可能的话,我想用那些浪费的 CPU 周期来处理图像。 (当然,这意味着必须始终对“陈旧”一帧的图像进行处理,但在 30 fps 下它实际上是实时的)。

我找到了一些 example code它使用 pthread_mutex_lock()pthread_mutex_control() 来保护共享数据,但似乎这些仍然会阻止“处理”线程在等待图像时运行通过 select() 的数据。更具体地说,这里有一些伪代码来说明我的担忧。 (注意:我意识到这些线程需要包含循环和其他检查,如上面链接的示例才能真正正常工作。)

void* capture()
{
pthread_mutex_lock(&mutex); // protect shared data
pthread_cond_wait(&space_avail,&mutex); // make sure the buffer has room

/// capture code... ///

select(fd+1, &fds, NULL, NULL, &tv); // waiting for data...
// Want to be processing frames
// during select, but won't the
// processing thread be blocked
// by the mutex lock?

// store image to the frame buffer

/// more capture code... ///

pthread_cond_signal(&data_avail);
pthread_mutex_unlock(&mutex);
}


void* process()
pthread_mutex_lock(&mutex);
pthread_cond_wait(&data_avail);

// access the most recently stored frame from the buffer

/// Do image processing ///

pthread_mutex_signal(&space_avail);
pthread_mutex_unlock(&mutex);
}

最佳答案

如果我正确理解了您的问题,您希望避免程序等待选择时浪费的繁忙等待周期,然后利用它进行图像处理。如果我错了,请纠正我。

根据我的经验,一种简单的方法是为选择 API 指定一个小的超时时间。 Select API 将等待超时。如果在此期间它从网络摄像头接收到任何数据,则 select 的返回值将不为零。如果在该持续时间内没有发现任何有趣的内容,则返回值为 0。

所以你的伪代码可以修改成如下:

void* capture(){
while(true){//iterate how many times you feel it is valid to
if (select(fd+1, &fds, NULL, NULL, &tv)!=0){
//We have found something here.take data from the webcam.
//break from the loop.
break;
}else{
//timeout occurred. process the image.
}
}
//process the data from the webcam
}

如果这能解决您的问题,请告诉我。有关 Select API 的更多信息,请访问: http://linux.die.net/man/2/select

关于c - 使用 select() 调用文件 I/O 的 Pthread 生产者/消费者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19554058/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com