4

「スレッドセーフ」キューに追加する 2 つのスレッドがあります。ただし、2 番目のスレッドがコンテンツを「プッシュ」しようとした場合。コンシューマーには、コンテンツが利用可能であることは通知されません。キューは増え続けますが、notify_one() はコンシューム メソッドの条件を通知しません。どうしてこれなの?

#ifndef CONCURRENT_QUEUE_H
#define CONCURRENT_QUEUE_H

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

template<typename Data>
class concurrent_queue {
private:
    std::queue<Data> the_queue;
    mutable boost::mutex the_mutex;
    boost::condition_variable the_condition_variable;
public:
    void push(Data const& data) {
        boost::mutex::scoped_lock lock(the_mutex);
        the_queue.push(data);
        lock.unlock();
        the_condition_variable.notify_one();
    }

    void wait_and_pop(Data& popped_value) {
        boost::mutex::scoped_lock lock(the_mutex);
        while(the_queue.empty()) {
            the_condition_variable.wait(lock);
        }

        popped_value=the_queue.front();
        the_queue.pop();
    }
};
#endif

このコードは、Boost 1.51.0 を使用する Fedora 14 では機能しますが、Windows 7 の Boost 1.50.0 では機能しません。

INCLUDEPATH += \
    . \
    /home/mehoggan/Devel/x86-fps/boost_1_50_0/include

LDFLAGS += -Wl,-rpath=/home/mehoggan/Devel/x86-fps/boost_1_50_0/lib

LIBS += \
    -L/home/mehoggan/Devel/x86-fps/boost_1_50_0/lib \
    -lboost_system \
    -lboost_thread \
    -lz

#ifndef CONCURRENT_QUEUE_H
#define CONCURRENT_QUEUE_H

#include <queue>
#include <boost/thread.hpp> // Using boost 1.50.0

template<typename Data>
class concurrent_queue {
private:
    std::queue<Data> the_queue;
    mutable boost::mutex the_mutex;
    boost::condition_variable the_condition_variable;
public:
    void push(Data const& data) {
        boost::mutex::scoped_lock lock(the_mutex);
        the_queue.push(data);
        lock.unlock();
        the_condition_variable.notify_all();
    }

    void wait_and_pop(Data& popped_value) {
        boost::mutex::scoped_lock lock(the_mutex);
        while(the_queue.empty()) {
            the_condition_variable.wait(lock);
        }

        popped_value=the_queue.front();
        the_queue.pop();
    }
};
#endif

concurrent_queue<int> the_queue;

void thread1func() {
    do {
        the_queue.push(1);
    } while (true);
}

void thread2func() {
    do {
        the_queue.push(2);
    } while (true);
}

void thread3func() {
    do {
        int read;
        the_queue.wait_and_pop(read);

        std::cout << "I read from thread " << read << std::endl;
    } while (true);
}

int main(int argc, char *argv[]) {
    boost::thread thread1 = boost::thread(thread1func);
    boost::thread thread2 = boost::thread(thread2func);
    boost::thread thread3 = boost::thread(thread3func);

    thread1.join();
    thread2.join();
    thread3.join();
}
4

1 に答える 1

0

あなたの Makefile は -pthread/-mthreads を使用していないようです。一般に、マルチスレッド コードを生成するようにコンパイラに要求していない場合、コードがまったく機能するとは思わないでください。

于 2013-03-20T22:34:56.477 に答える