gpt4 book ai didi

c++ - 在简单的 C++ OpenCV 项目中使用 pthread

转载 作者:太空宇宙 更新时间:2023-11-03 22:27:35 26 4
gpt4 key购买 nike

我正在尝试在我的 OpenCV 项目中使用 pthread。最初我只是尝试使用两个不同的线程打开两个不同的图像。在Windows7 + VS2010 + pthreads-win32 lib上,程序运行良好。

但在我的 Debian jessei 机器(Opencv 2.4.1)上,相同的代码虽然编译得很好,但它的执行崩溃并出现以下错误。

[xcb] Unknown request in queue while dequeuing
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
[xcb] Aborting, sorry about that.
pthreadTest: ../../src/xcb_io.c:179: dequeue_pending_request: Assertion `!xcb_xlib_unknown_req_in_deq' failed.
Aborted

有趣的是,当只创建 1 个线程时 [for (i=0; i<1; i++)],它运行良好,并显示图像。

我已经花了 1.5 天的时间试图解决它,但没有成功。有谁知道,我做错了什么?

代码如下:

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <cstdio>
#include <iostream>
#include <pthread.h>

using namespace cv;
using namespace std;

struct thread_data {
bool isBig;
string fileName;
};


void *processImg(void *args)
{
struct thread_data *data = (struct thread_data *) args;
const char * inputImgWinName = data->isBig ? "Big Img" : "Small Img";

cv::Mat imgInput = imread(data->fileName, 1);

cv::namedWindow(inputImgWinName, cv::WINDOW_AUTOSIZE);
cv::imshow(inputImgWinName, imgInput);

cv::waitKey();
pthread_exit(NULL);
//return NULL;
}


int main( int argc, char** argv )
{
struct thread_data data[2];

data[0].isBig = true;
data[0].fileName = "img1.png";

data[1].isBig = false;
data[1].fileName = "img2.png";

pthread_t threads[2];
pthread_attr_t attr;
void *status;

// Initialize and set thread joinable
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

// Create Threads
int rc;
for (int i=0; i<2; i++) {
rc = pthread_create(&threads[i], &attr, processImg, (void *)&(data[i]));
if (rc) {
cout << "Error: Unable to create thread";
return -1;
}
}

// free attribute and wait for the other threads
pthread_attr_destroy(&attr);
for (int i=0; i<2; i++) {
rc = pthread_join(threads[i], &status);
if (rc){
cout << "Error:unable to join," << rc << endl;
exit(-1);
}
cout << "Thread: "<< i <<" exiting with status: " << status << endl;
}

pthread_exit(NULL);
return 0;
}

PS:由于某些原因,我无法使用 C++11 thread.h

最佳答案

namedWindow,waitKey 应该离开你的线程,你在这里干扰桌面/gui

关于c++ - 在简单的 C++ OpenCV 项目中使用 pthread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35237460/

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