C ++ 11线程段错误

时间:2018-03-18 13:36:20

标签: c++ multithreading c++11 thread-safety mutex

现在我学习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 Ошибка сегментирования (стек памяти сброшен на
> диск)

1 个答案:

答案 0 :(得分:1)

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

在你的情况下proxy_list,它的std::vector不是线程安全的(而且std::stringint里面都是不是线程安全的)。更改只能在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()调用期间不得锁定互斥锁,因为它具有最长的执行时间,而其他线程将等待只有一个正在运行,从而使整个程序按顺序执行。