在多线程OpenCV程序中使用信号报警

时间:2016-11-08 12:11:29

标签: c++ linux multithreading opencv

我正在写一个OpevCV程序,一个多线程程序,其中一个线程应该收到 alarm 信号。它有点复杂。为了显示问题出在哪里,我写了测试代码,如下所示:

MainThread:

int main(int argc,char **argv)
{ 
   cout << "main thread = " << pthread_self() << endl;
   sigset_t set;
   sigemptyset(&set);
   sigaddset(&set, SIGALRM);
   pthread_sigmask(SIG_BLOCK, &set, NULL);

   struct sigaction sa;
   sa.sa_handler = int_handler;
   sa.sa_flags |= SA_INTERRUPT;
   sigaction(SIGALRM,&sa,NULL);

   pthread_t thread;
   if(pthread_create(&thread, NULL, capturePictures, NULL) < 0)
   {
       cerr << "pthread_create error" << endl;
       return -1;
   }
   alarm(5);
   pthread_join(thread, NULL);
   return 0;
}

ChildThread:

void *capturePictures(void* arg)
{
    cout << "capturePictures thread = " << pthread_self() << endl;
    sigset_t set;
    sigemptyset(&set);
    sigaddset(&set, SIGALRM);
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);

    string rtsp = "rtsp://admin:admin12345@192.168.0.81:554/h264/cha1/main/av_stream";

    VideoCapture vcap;
    if(!vcap.open(rtsp)) {
        cout << "open stream error" << endl;
        return (void *)-1;
    }

    unsigned int picIndex = 0;
    int index = 0;
    Mat image;

    while(1){
        if (!vcap.read(image)){
            cout <<"read image error" << endl;
            return (void*)-1;
        }

        if (picIndex++ % 25 != 0) continue;

        char fileName[30];
        sprintf(fileName,"pictures/%d.jpg",++index);
        imwrite(fileName, image);
    }
}

int_handler:

void int_handler(int signum)
{
    cout << "int_handler = " << pthread_self() << endl;
}

此测试代码并不代表anthing,只是想告诉您问题所在。 输出是这样的:

main thread = 140334223800320
capturePictures thread = 140333923575552
int_handler = 140333931968256

在主线程中没有调用int_handler,也没有在capturePictures线程(子线程)中调用,我甚至不知道哪个线程的id是 140333931968256 ,我只创建一个子线程...... 如果我想实现目标,我该怎么办?

0 个答案:

没有答案