C++11 线程段错误

C++11 threads segfault

本文关键字:错误 线程 段错误 C++11      更新时间:2023-10-16

现在我学习C++多线程。我写了一个简单的代理检查器。但是我不知道如何解决我遇到的问题:

我想我需要使用 std::mutex。但是我找不到它可以工作的地方。

.h:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <thread>
#include <deque>
#include <utility>
#include <mutex>
#include <curlpp/cURLpp.hpp>
#include <curlpp/Easy.hpp>
#include <curlpp/Options.hpp>
class ProxyChecker
{
public:
    ProxyChecker();
    ~ProxyChecker();
    bool check_proxy(std::string&, int&);
    void parse_file();
    void print_list();
    void parse_list();
private:
    std::mutex                               m_mutex;
    std::string                              file_name = "./vipsocks.txt";
    std::deque<std::pair<std::string, int>>  proxy_list;
    std::vector<std::thread>                 threads;
};

。.cpp:

#include "proxy_checker.h"
ProxyChecker::ProxyChecker()
{
    this->parse_file();  
    this->print_list();
    try {
        for(int i = 0; i < 10; i++) {
            threads.push_back(std::thread(&ProxyChecker::parse_list, this));
        }
        for(int i = 0; i < 10; i++) {
            threads[i].join();
        }
    } catch(const std::exception &ex) {
        std::cout << ex.what() << std::endl;
    }
}
ProxyChecker::~ProxyChecker()
{
}
void ProxyChecker::print_list()
{
    for(auto it : proxy_list) {
        std::cout << it.first << ":" << it.second << std::endl;
    }
    std::cout << std::endl;
}
void ProxyChecker::parse_file()
{
    std::cout << "[FILE PARSING]" << std::endl;
    std::fstream fin(this->file_name);
    std::string  token;
    std::string  sep(":");
    while(getline(fin, token)){
        std::string::size_type pos = token.find(sep);
        std::string ip             = token.substr(0, pos);
        int port                   = std::stoi(token.substr(pos + sep.length()));        
        if((ip != "") && (port > 0)) {
            this->proxy_list.push_back(std::pair<std::string, int>(ip, port));
        }
    }
    fin.close();
    std::cout << std::endl << "[FILE PARSED]" << std::endl << std::endl;
}
void ProxyChecker::parse_list()
{
    while(!this->proxy_list.empty()) {
        if(check_proxy(proxy_list.front().first, proxy_list.front().second) == true) {
            std::cout << "[IP]: " << proxy_list.front().first << " [PORT]: " << proxy_list.front().second << " ";
            std::cout << "[SIZE]: " << proxy_list.size() << std::endl;
        }
        proxy_list.pop_front();
    }
}
bool ProxyChecker::check_proxy(std::string &ip, int &port)
{
    std::stringstream os;
    try {
        curlpp::Cleanup m_cleanup;
        curlpp::Easy    m_request;
        m_request.setOpt(curlpp::Options::Url("http://goole.com"));
        m_request.setOpt(curlpp::Options::Proxy(ip));
        m_request.setOpt(curlpp::Options::ProxyPort(port));
        m_request.setOpt(curlpp::Options::WriteStream(&os));
        m_request.setOpt(curlpp::Options::Timeout(10));
        m_request.perform();
    } catch(curlpp::RuntimeError & e) {
        std::cout << e.what() << std::endl;
        return false;
    } catch(curlpp::LogicError & e) {
        std::cout << e.what() << std::endl;
        return false;
    }
    return true;
}

请问你能告诉我我的代码有什么问题吗?

当程序工作时,这是错误:

> [IP]: 118.139.178.67 [PORT]: 24353 [SIZE]: 12 Operation timed out
> after 10000 milliseconds with 0 bytes received Operation timed out
> after 10000 milliseconds with 0 bytes received Operation timed out
> after 10001 milliseconds with 0 bytes received Operation timed out
> after 10001 milliseconds with 0 bytes received Operation timed out
> after 10001 milliseconds with 0 bytes received Operation timed out
> after 10001 milliseconds with 0 bytes received Operation timed out
> after 10000 milliseconds with 0 bytes receivedOperation timed out
> after 10000 milliseconds with 0 bytes received Operation timed out
> after 10000 milliseconds with 0 bytes received Failed to connect to
> 118.190.137.100 port 12345: Connection refused [IP]: 138.210.210.107 [PORT]: 37080 [SIZE]: 1 [IP]:  [PORT]: 0 [SIZE]: 0 [IP]:  [PORT]: 0
> [SIZE]: 18446744073709551615 [IP]:  [PORT]: [IP]: 0  [PORT]: [SIZE]: 0
> [SIZE]: 1844674407370955161418446744073709551614 [IP]:  [PORT]: 0
> [SIZE]: 18446744073709551612 [IP]:  [PORT]: 0 [SIZE]:
> 18446744073709551611 [IP]:  [PORT]: 0 [SIZE]: 18446744073709551610
> [IP]:  [PORT]: 0 [SIZE]: 18446744073709551609 [IP]:  [PORT]: 0 [SIZE]:
> 18446744073709551608 [IP]:  [PORT]: 0 [SIZE]: 18446744073709551607
> [IP]:  [PORT]: 0 [SIZE]: 18446744073709551606 [IP]:  [PORT]: 0 [SIZE]:
> 18446744073709551605 Ошибка сегментирования (стек памяти сброшен на
> диск)

使用互斥锁,您必须保护由多个线程访问且不是线程安全的变量。

在您的情况下,这将是

proxy_list,它是std::vector不是线程安全的(而且它里面的std::string s和int不是线程安全的(。更改只能在parse_list()中完成。代码如下:

void ProxyChecker::parse_list()
{
    std::string proxy_str;
    int proxy_int;
    size_t list_size;
    while(true) {
        {
            std::lock_guard lock(m_mutex);
            if(proxy_list.empty())
                return;
            proxy_str = proxy_list.front().first;
            proxy_int = proxy_list.front().second;
            list_size = proxy_list.size();
            proxy_list.pop_front();
        }
        if(check_proxy(proxy_str, proxy_int) == true) {
            std::cout << "[IP]: " << proxy_str << " [PORT]: " << proxy_int << " ";
            std::cout << "[SIZE]: " << list_size << std::endl;
        }
    }
}

这里重要的是,互斥锁仅在读取/更改proxy_list时被锁定。互斥check_proxy()调用期间不得锁定,因为这具有最长的执行时间,并且其他线程将在只有一个线程运行时等待,从而使整个程序按顺序执行。