-1

boost::thread に基づいて 1 行ずつ読み取り、処理、書き込みを並列に実装したいのですが、現在のバージョンの動作は不定です。次のテストでは、読み取り (同時) キューを満たすことで CSV ファイルを読み取ります。出力ファイルに書き込まれる書き込みキュー (現時点では処理なし)。

発生した問題:

  • Windows と Unix の両方で、プログラムはランダムに終了せず (~3/5 回)、SIGSEGV を生成します (~1/100)
  • Unix では、多くのエラーがあります。スレッドの作成時の SIGABRT、作成後の「割り当てられたブロックの前にメモリがクローバーされました」(-> SIGABRT も)、ランダムに 1 ~ 15 行。

問題とコードを教えて、他の人に答えてもらうのは嫌いですが (私は時々あなたの側にいます)、信じてください、それを修正するために他に何も考えられません (スレッドの扱い、デバッグは悪夢です)ので、あらかじめお詫び申し上げます。ここにあります :

Main.cpp :

#include "io.hpp"

#include <iostream>

int main(int argc, char *argv[]) {
    CSV::Reader reader;
    CSV::Writer writer;

    if(reader.open("test_grandeur_nature.csv") && writer.open("output.txt")) {
        CSV::Row row;

        reader.run(); //Reads the CSV file and fills the read queue
        writer.run(); //Reads the to-be-written queue and writes it to a txt file

        //The loop is supposed to end only if the reader is finished and empty
        while(!(reader.is_finished() && reader.empty())) {
            //Transfers line by line from the read to the to-be-written queues
            reader.wait_and_pop(row);
            writer.push(row);
        }
        //The reader will likely finish before the writer, so he has to finish his queue before continuing.
        writer.finish(); 
    }
    else {
        std::cout << "File error";
    }

    return EXIT_SUCCESS;
}

Io.hpp :

#ifndef IO_H_INCLUDED
#define IO_H_INCLUDED

#include "threads.hpp"

#include <fstream>

namespace CSV {
    class Row {
        std::vector<std::string> m_data;

        friend class Iterator;
        friend void write_row(Row const &row, std::ostream &stream);

        void read_next(std::istream& csv);

        public:
            inline std::string const& operator[](std::size_t index) const {
                return m_data[index];
            }
            inline std::size_t size() const {
                return m_data.size();
            }
    };

    /** Reading *************************************************************************/

    class Iterator {
        public:
            Iterator(std::istream& csv) : m_csv(csv.good() ? &csv : NULL) {
                ++(*this);
            }
            Iterator() : m_csv(NULL) {}

            //Pre-Increment
            Iterator& operator++() {
                if (m_csv != NULL) {
                    m_row.read_next(*m_csv);
                    m_csv = m_csv->good() ? m_csv : NULL;
                }

                return *this;
            }
            inline Row const& operator*() const {
                return m_row;
            }

            inline bool operator==(Iterator const& rhs) {
                return ((this == &rhs) || ((this->m_csv == NULL) && (rhs.m_csv == NULL)));
            }
            inline bool operator!=(Iterator const& rhs) {
                return !((*this) == rhs);
            }
        private:
            std::istream* m_csv;
            Row m_row;
    };

    class Reader : public Concurrent_queue<Row>, public Thread {
        std::ifstream m_csv;

        Thread_safe_value<bool> m_finished;

        void work() {
            if(!!m_csv) {
                for(Iterator it(m_csv) ; it != Iterator() ; ++it) {
                    push(*it);
                }
                m_finished.set(true);
            }
        }

    public:
        Reader() {
            m_finished.set(false);
        }

        inline bool open(std::string path) {
            m_csv.open(path.c_str());

            return !!m_csv;
        }

        inline bool is_finished() {
            return m_finished.get();
        }
    };

    /** Writing ***************************************************************************/

    void write_row(Row const &row, std::ostream &stream);

    //Is m_finishing really thread-safe ? By the way, is it mandatory ?
    class Writer : public Concurrent_queue<Row>, public Thread {
        std::ofstream m_csv;

        Thread_safe_value<bool> m_finishing;

        void work() {
            if(!!m_csv) {
                CSV::Row row;

                while(!(m_finishing.get() && empty())) {
                    wait_and_pop(row);
                    write_row(row, m_csv);
                }
            }
        }

    public:
        Writer() {
            m_finishing.set(false);
        }

        inline void finish() {
            m_finishing.set(true);
            catch_up();
        }

        inline bool open(std::string path) {
            m_csv.open(path.c_str());

            return !!m_csv;
        }
    };
}

#endif

Io.cpp :

#include "io.hpp"

#include <boost/bind.hpp>
#include <boost/tokenizer.hpp>

void CSV::Row::read_next(std::istream& csv) {
    std::string row;
    std::getline(csv, row);

    boost::tokenizer<boost::escaped_list_separator<char> > tokenizer(row, boost::escaped_list_separator<char>('\\', ';', '\"'));
    m_data.assign(tokenizer.begin(), tokenizer.end());
}

void CSV::write_row(Row const &row, std::ostream &stream) {
    std::copy(row.m_data.begin(), row.m_data.end(), std::ostream_iterator<std::string>(stream, ";"));
    stream << std::endl;
}

Threads.hpp :

#ifndef THREADS_HPP_INCLUDED
#define THREADS_HPP_INCLUDED

#include <boost/bind.hpp>
#include <boost/thread.hpp>

class Thread {
protected:
    boost::thread *m_thread;

    virtual void work() = 0;

    void do_work() {
        work();
    }

public:
    Thread() : m_thread(NULL) {}
    virtual ~Thread() {
        catch_up();
        if(m_thread != NULL) {
            delete m_thread;
        }
    }

    inline void catch_up() {
        if(m_thread != NULL) {
            m_thread->join();
        }
    }

    void run() {
        m_thread = new boost::thread(boost::bind(&Thread::do_work, boost::ref(*this)));
    }
};

/** Thread-safe datas **********************************************************/

#include <queue>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>

template <class T>
class Thread_safe_value : public boost::noncopyable {
    T m_value;
    boost::mutex m_mutex;

    public:
        T const &get() {
            boost::mutex::scoped_lock lock(m_mutex);
            return m_value;
        }
        void set(T const &value) {
            boost::mutex::scoped_lock lock(m_mutex);
            m_value = value;
        }
};

template<typename Data>
class Concurrent_queue {
    std::queue<Data> m_queue;
    mutable boost::mutex m_mutex;
    boost::condition_variable m_cond;

public:
    void push(Data const& data) {
        boost::mutex::scoped_lock lock(m_mutex);
        m_queue.push(data);
        lock.unlock();
        m_cond.notify_one();
    }

    bool empty() const {
        boost::mutex::scoped_lock lock(m_mutex);
        return m_queue.empty();
    }

    void wait_and_pop(Data& popped) {
        boost::mutex::scoped_lock lock(m_mutex);
        while(m_queue.empty()) {
            m_cond.wait(lock);
        }

        popped = m_queue.front();
        m_queue.pop();
    }
};

#endif // THREAD_HPP_INCLUDED

このプロジェクトは重要であり、あなたが私を助けてくれれば本当に感謝しています =)

よろしくお願いします。

よろしく、

ミステールさん。

4

2 に答える 2

1

完了ロジックにエラーがあります。

ループはキューから最後のエントリを読み取り、フラグが設定される前に次のmain()エントリを待機してブロックします。m_finished

への呼び出しの前に長時間待機するとm_finished.set(true)( sleep(5)Linux やSleep(5000)Windows で 5 秒間待機するなど)、コードは毎回ハングします。

(これは、おそらく別のものであるセグフォルトまたはメモリ割り当てエラーに対処しません)

問題のある実行は次のようになります。

  1. リーダー スレッドは、ファイルから最後の項目を読み取り、キューにプッシュします。
  2. メインスレッドはキューから最後のアイテムをポップします。
  3. メイン スレッドは、ライター スレッドのキューの最後のアイテムをプッシュします。
  4. メインスレッドはループします。m_finishedは設定されていないため、 を呼び出しますwait_and_pop
  5. リーダー スレッドは、それがファイルの最後にあることを認識し、 を設定しますm_finished
  6. メイン スレッドはリーダー キューで別のアイテムを待機してブロックされますが、リーダーはアイテムを提供しません。

スリープ コールは、リーダー スレッドのステップ 1 と 5 の間に大きな遅延を置くことで、このイベントの順序を強制するため、メイン スレッドはステップ 2 から 4 を実行する機会が十分にあります。これは、競合状態のデバッグに役立つテクニックです。

于 2010-07-12T12:31:45.933 に答える
-1

私が見つけた唯一の明らかな問題を簡単に読んだ後、それはおそらくあなたの問題のいくつか(すべてではないかもしれません)を説明するでしょうConcurrent_queue::push.

スコープ付きミューテックスを呼び出していることに気付いたときはいつでもunlock()、何かがおかしいことを示しているはずです。スコープ付きミューテックスを使用する主なポイントの 1 つは、オブジェクトがスコープに出入りするときにロックとロック解除が暗黙的に行われることです。ロックを解除する必要がある場合は、コードを再構築する必要がある場合があります。

ただし、この場合、実際にコードを再構築する必要はありません。この場合、ロック解除は間違っています。条件が通知されると、ミューテックスをロックする必要があります。信号が発生するとロックが解除されます。したがって、ロック解除を次のコードに置き換えることができます。

void push(Data const& data) {
    boost::mutex::scoped_lock lock(m_mutex);
    m_queue.push(data);
    m_cond.notify_one();
}

条件が通知された後、関数が戻ったときにミューテックスのロックを解除します。

于 2010-07-11T15:26:00.197 に答える