除了主线程,想开另一个线程,大多数时间这个线程都不运行,只有某个键被按下时那个线程才被激活,响应完之后继续处于等待状态。如下面程序所示。在收到按键时,调用 int rc = pthread_create(&camera_control_thread, NULL, Camera_Control_Thread, (void *)&mydata); 开始相机控制线程。不知道这样行吗?只有在程序结束前 pthread_join(camera_control_thread, &exit_disp); pthread_mutex_destroy(&dispwindow);才被调用,而pthread_create却多次调用,这样行吗?
code = c]
int main(int argc, char * argv[])
{
cvNamedWindow("Ori", CV_WINDOW_NORMAL);
cvSetWindowProperty("Ori", CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN);
while(1)
{
cap >> frame;
if((frame.rows > 0) && (frame.cols > 0))
{
int key_input=cv::waitKey(1)%256;
if(key_input!=-1)
{
mydata.keyInput = key_input;
int rc = pthread_create(&camera_control_thread, NULL, Camera_Control_Thread, (void *)&mydata);
if(0 != rc)
{
break;
}
}
if(key_input == 'q' || key_input == 'Q' )
{
break;
}
}
}
printf("frame rates = %f\n",(double)nn/t);
pthread_join(camera_control_thread, &exit_disp);
pthread_mutex_destroy(&dispwindow);
return 0;
}
[/code]
调用pthread_cond_wait后,mutex会重新加锁,如果按键过于频繁,或thread中的处理时间较长,由于在waitKey中调用了mutex_lock,会阻塞主程序。
为了避免这种情况,需要修改一下代码:
static void * camera_control_thread(void * param)
{
int key;
//
while(1)
{
// 先锁定,再检查是否达到运行条件
pthread_mutex_lock(&g_mutex);