特定的线程数c ++

时间:2014-04-10 20:24:08

标签: c++ multithreading web-crawler libcurl gumbo

我正在用c ++编写一个爬虫,函数crawler下载一个网站并从中提取所有链接。我希望它在多个线程中运行函数crawler,每个线程具有不同的参数,我还想指定线程数量。所以在程序开始时我想指定一些线程,然后当程序启动时我需要每个线程运行不同的参数,这样我就可以同时下载指定数量的网站。我知道如何进行基本的多线程,但我需要在程序开始时指定一些线程。那么有没有可以让我这样做的图书馆?或者可以使用std::thread

#include <sstream>
#include <iostream>
#include <string>
#include "gumbo.h"
#include <curl/curl.h>
using namespace std;

//extract links
static void search_for_links(GumboNode* node) {
  if (node->type != GUMBO_NODE_ELEMENT) {
    return;
  }
  GumboAttribute* href;
  if (node->v.element.tag == GUMBO_TAG_A &&
      (href = gumbo_get_attribute(&node->v.element.attributes, "href"))) {
    std::cout << href->value << std::endl;
  }

  GumboVector* children = &node->v.element.children;
  for (int i = 0; i < children->length; ++i) {
    search_for_links(static_cast<GumboNode*>(children->data[i]));
  }

}



//turn the output from libcurl in to a string
size_t write_to_string(void *ptr, size_t size, size_t count, void *stream) {
((string*)stream)->append((char*)ptr, 0, size*count);
return size*count;
}

int crawler(char url[60])
{


curl_global_init( CURL_GLOBAL_ALL );
CURL * myHandle = curl_easy_init ( );



//set the 'libcurl' parameters

curl_easy_setopt(myHandle, CURLOPT_USERAGENT, "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16");
curl_easy_setopt(myHandle, CURLOPT_AUTOREFERER, 1 );
curl_easy_setopt(myHandle, CURLOPT_FOLLOWLOCATION, 1 );
curl_easy_setopt(myHandle, CURLOPT_COOKIEFILE, "");

//set the url
curl_easy_setopt(myHandle, CURLOPT_URL, url);

//turn the output in to a string using a function

string response;
curl_easy_setopt(myHandle, CURLOPT_WRITEFUNCTION, write_to_string);
curl_easy_setopt(myHandle, CURLOPT_WRITEDATA, &response);
curl_easy_perform( myHandle );
//HTML parsing

GumboOutput* output = gumbo_parse(response.c_str());
search_for_links(output->root);



return 0;
}

int main()
{
    crawler("http://wikipedia.org");
return 0;   
}

1 个答案:

答案 0 :(得分:1)

您可以创建许多std :: threads并将它们存储在向量中。让我们说你有你的功能

void f(int x, std::string const& y);

然后你可以使用

创建一个带有运行函数的线程的向量
std::vector<std::thread> threadgroup;
threadgroup.emplace_back(1, "abc");
threadgroup.emplace_back(2, "def");

这将在向量中启动两个线程。确保在退出之前加入该线程。

我认为你实际上需要一定数量的线程来处理带链接的容器。每个线程下载一个页面并添加到容器的新链接。处理一个页面时,它从容器中获取一个新链接。