特定数量的线程c++
Specific number of threads c++
我正在用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;
}
您可以创建许多std::线程并将它们存储在向量中。假设你有你的功能
void f(int x, std::string const& y);
然后,您可以创建一个向量,其中线程运行函数
std::vector<std::thread> threadgroup;
threadgroup.emplace_back(1, "abc");
threadgroup.emplace_back(2, "def");
这将在一个向量中启动两个线程。退出前请确保加入线程。
我认为您实际上需要一定数量的线程来处理带有链接的容器。每个线程下载一个页面,并向容器添加新的链接。当一个页面被处理时,它会从容器中获取一个新的链接。
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 在C++中使用cURL和多线程
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在cuda线程之间共享大量常量数据
- 如何将元素添加到数组的线程安全函数?
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 异常属于C++中的线程还是进程
- C++中的线程安全删除
- C++使用params创建线程函数会导致转换错误
- 类与私有变量的其他类之间的线程安全性
- CoInitialize()在单独的线程上崩溃而不返回
- c++中的线程池
- 线程之间的布尔停止信号
- 为什么std::async使用同一个线程运行函数
- 用于矢量处理的多个线程
- C++为线程工作动态地分割例程
- 为什么我不能在 while 循环中创建线程?