jjzjj

c++ - 多线程 curl 请求的段错误

coder 2023-06-21 原文

我在使用 C++ 程序时遇到了一些问题。基本上我已经为 http 请求编写了一个简单的包装器,能够一次执行多个请求。 工作得很好,但是当我做 httpS 请求时,它在多线程模式下随机崩溃。我正在使用 curl 和 posix 线程。 回溯看起来像这样:

======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x80996)[0x7fea9046d996]
/lib/x86_64-linux-gnu/libc.so.6(+0x82b80)[0x7fea9046fb80]
/lib/x86_64-linux-gnu/libc.so.6(realloc+0xf2)[0x7fea90470ae2]
/lib/x86_64-linux-gnu/libcrypto.so.1.0.0(CRYPTO_realloc+0x49)[0x7fea8f9c6169]
/lib/x86_64-linux-gnu/libcrypto.so.1.0.0(lh_insert+0x101)[0x7fea8fa4bfb1]
/lib/x86_64-linux-gnu/libcrypto.so.1.0.0(+0xe844e)[0x7fea8fa4e44e]
/lib/x86_64-linux-gnu/libcrypto.so.1.0.0(ERR_get_state+0xde)[0x7fea8fa4eeee]
/lib/x86_64-linux-gnu/libcrypto.so.1.0.0(ERR_clear_error+0x15)[0x7fea8fa4f065]
/usr/lib/x86_64-linux-gnu/libcurl.so.4(+0x24e79)[0x7fea90f10e79]
/usr/lib/x86_64-linux-gnu/libcurl.so.4(+0x39ea0)[0x7fea90f25ea0]
/usr/lib/x86_64-linux-gnu/libcurl.so.4(+0xf8fd)[0x7fea90efb8fd]
/usr/lib/x86_64-linux-gnu/libcurl.so.4(+0x219f5)[0x7fea90f0d9f5]
/usr/lib/x86_64-linux-gnu/libcurl.so.4(+0x35538)[0x7fea90f21538]
/usr/lib/x86_64-linux-gnu/libcurl.so.4(curl_multi_perform+0x91)[0x7fea90f21d31]
/usr/lib/x86_64-linux-gnu/libcurl.so.4(curl_easy_perform+0x107)[0x7fea90f19457]
./exbot[0x40273a]
/lib/x86_64-linux-gnu/libpthread.so.0(+0x7f6e)[0x7fea90cd6f6e]
/lib/x86_64-linux-gnu/libc.so.6(clone+0x6d)[0x7fea904e79cd]

这可能是 libcrypto 中的错误吗? 我能以某种方式告诉 curl 不要使用 libcrypto 吗?还有其他选择吗? 它只会在使用 httpS 请求时崩溃,并且即使同时处理 10000 个 http 查询也能正常工作。

干杯, 托马斯

只是为了完整我的代码:

// simple wrapper for http requests

#ifndef _REQUEST_H_
#define _REQUEST_H_


#include <curl/curl.h>
#include <pthread.h>
#include <string>
#include <iostream>


//////////////////////////////////
// MACROS
//////////////////////////////////
#define ERR(_msg) std::cerr << __FUNCTION__ << ": " << _msg << std::endl


//////////////////////////////////
// REQUEST WRAPPER
//////////////////////////////////
typedef unsigned int uint;
class RequestWrapper
{
private: // non copyable
    RequestWrapper();
    RequestWrapper(const RequestWrapper &that);
    RequestWrapper &operator=(const RequestWrapper &that);

public:
    struct Response
    {
        Response() : msg(""), success(false) {}
        std::string msg;
        bool success;
    };

    static Response simpleGET(std::string url, uint timeout);
    static size_t write(char *content, size_t size, size_t nmemb, void *userp);
};


//////////////////////////////////
// GET
//////////////////////////////////
inline size_t RequestWrapper::write(char *content, size_t size, size_t nmemb, void *userp)
{
    std::string *buf = static_cast<std::string *>(userp);
    size_t realsize = size * nmemb;
    for (uint i = 0; i < realsize; ++i)
    {
        buf->push_back(content[i]);
    }
    return realsize;
}
inline RequestWrapper::Response RequestWrapper::simpleGET(std::string url, uint timeout)
{
    Response resp;
    CURL *curl;
    CURLcode res;
    std::string buf;

    // send request
    buf.clear();
    curl = curl_easy_init();
    if (!curl)
    {
        //ERR("libcurl init failed");
        return resp;
    }
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, static_cast<void *>(&buf));
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
    res = curl_easy_perform(curl);
    if(res != CURLE_OK)
    {
        //ERR("libcurl request failed, CODE: " << res);
        return resp;
    }
    curl_easy_cleanup(curl);

    // done
    resp.msg = buf;
    resp.success = true;
    return resp;
}


//////////////////////////////////
// MULTITHREADED REQUEST
//////////////////////////////////
class RequestList
{
private:
    std::vector<std::string> _reqs;
    static void *sender(void *payload);
    static pthread_mutex_t _mutex;

public:
    inline void add(std::string request)
    {
        _reqs.push_back(request);
    }

    inline void clear()
    {
        _reqs.clear();
    }

    std::vector<std::string> send(uint timeout) const;

    struct Payload
    {
        std::string url;
        std::vector<std::string> *out;
        uint tout, index;
        Payload(std::string url,
                std::vector<std::string> *out,
                uint tout, uint index) : url(url), out(out), tout(tout), index(index) { }
        Payload() : url(""), out(NULL), tout(0), index(0) { }
    };
};


//////////////////////////////////
// SEND MT REQUEST
//////////////////////////////////
pthread_mutex_t RequestList::_mutex;
void *RequestList::sender(void *payload)
{
    Payload *pl = static_cast<Payload *>(payload);
    RequestWrapper::Response resp = RequestWrapper::simpleGET(pl->url, pl->tout);
    pthread_mutex_lock(&_mutex);
    if (resp.success)
    {
        pl->out->at(pl->index) = resp.msg;
        std::cerr << ".";
    }
    else
    {
        std::cerr << "x";
    }
    pthread_mutex_unlock(&_mutex);
    return NULL;
}
inline std::vector<std::string> RequestList::send(uint timeout) const
{
    std::vector<std::string> resp;
    resp.resize(_reqs.size());
    Payload *payloads = new Payload[_reqs.size()];
    pthread_t *tids = new pthread_t[_reqs.size()];

    // create mutex
    pthread_mutex_init(&_mutex, NULL);

    // prepare payload and create thread
    for (uint i = 0; i < _reqs.size(); ++i)
    {
        payloads[i] = Payload(_reqs[i], &resp, timeout, i);
        pthread_create(&tids[i], NULL, RequestList::sender, static_cast<void *>(&payloads[i]));
    }

    // wait for threads to finish
    for (uint i = 0; i < _reqs.size(); ++i)
    {
        pthread_join(tids[i], NULL);
    }
    std::cerr << std::endl;

    //destroy mutex
    pthread_mutex_destroy(&_mutex);

    delete[] payloads;
    delete[] tids;
    return resp;
}


#endif

最佳答案

Libcrypto 是 OpenSSL 的一部分,即 not thread-safe除非您提供必要的回调。根据documentation ,在符合 POSIX 的系统(具有线程本地 errno)上,默认的线程 ID 实现是可以接受的,因此您只需要一个锁定功能:

void locking_function(int mode, int n, const char *file, int line);

此函数需要维护一组 CRYPTO_num_locks() 互斥锁,并根据 mode< 的值锁定或解锁第="">n 个互斥锁。您可以阅读文档以获取更多详细信息。 libcurl网站居然有some sample code显示如何执行此操作。

或者,您可以使用线程安全的不同 SSL 库构建 libcurl,例如 GnuTLS .

关于c++ - 多线程 curl 请求的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24589362/

有关c++ - 多线程 curl 请求的段错误的更多相关文章

  1. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  2. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  3. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  4. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  5. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  6. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  7. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  8. ruby-on-rails - 错误 : Error installing pg: ERROR: Failed to build gem native extension - 2

    我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby​​'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe

  9. ruby - #之间? Cooper 的 *Beginning Ruby* 中的错误或异常 - 2

    在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee

  10. ruby-on-rails - 每次我尝试部署时,我都会得到 - (gcloud.preview.app.deploy) 错误响应 : [4] DEADLINE_EXCEEDED - 2

    我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie

随机推荐