Why the results different between each executing of the exe programmed in QT and libcurl?

StackOverflow https://stackoverflow.com/questions/21184762

  •  29-09-2022
  •  | 
  •  

Domanda

I would like to program a Qt programe with libcurl.

Header like this:

    class WorkThread : public QThread
{
Q_OBJECT
public:
     //...
      void work(QString url_);
      static size_t callback_get_head(void *ptr, size_t size, size_t nmemb, void *userp);
protected:
      void run();
private:
      QString url;    
};

Source code:

//....
void WorkThread::work(QString url_)
{   
    url=url_;    
    start();
}
void WorkThread::run()
{
    CURL *curl;
    CURLcode res;
    char buffer[512];
    curl = curl_easy_init();
    if(curl) {

      char *liburl=url.toLatin1().data();
      curl_easy_setopt(curl, CURLOPT_URL, liburl);
      curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WorkThread::callback_get_head); 
      curl_easy_setopt(curl, CURLOPT_WRITEDATA, buffer);
      res = curl_easy_perform(curl);
      if(res != CURLE_OK)
      printf("curl_easy_perform() failed: %s\n",curl_easy_strerror(res));
      curl_easy_cleanup(curl);
      printf("%s \n",buffer);
    }
}
size_t WorkThread::callback_get_head(void *ptr, size_t size, size_t nmemb, void *userp)
{
    strcat( (char*)(userp), (char*)(ptr));
       return size * nmemb;
}

In main :

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    WorkThread thread1;
    WorkThread thread2;
    WorkThread thread3;
    thread1.work("http://hq.sinajs.cn/list=sh601006");
    thread2.work("http://hq.sinajs.cn/list=sh601006");
    thread3.work("http://hq.sinajs.cn/list=sh601006");
    return a.exec();
}

When I compile and run , I find it that the results is different each time. What is wrong?It said "name resolve failed".But it seems that name resolve successed in thread1 and thread2.

È stato utile?

Soluzione

The problem is that you're not using QThread properly. Unless you're going to change how Qt handles threads, you shouldn't be inheriting from it; You're doing it Wrong!

Your main object has the thread affinity of the main thread, though your Curl object's thread affinity is the new thread.

Separate the Curl code into a separate class, inherited from QObject and then move that to the new thread. This should solve the problems you're seeing.

This article explains how to use QThread properly.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top