尝试实现线程池但是中止被称为

时间:2017-05-19 22:17:22

标签: c++ multithreading c++11 threadpool

我试图实现一个线程池一个生产者,几个消费者和我的线程在发生任何事情之前不断调用中止异常。

为了实现这一点,我使用了一个与condition_variable配对的互斥锁,该互斥用于保持线程等待,直到主程序线程通知存在需要处理的内容。我在visual studio 2015中使用c ++ 11。我很确定它与等待机制有关,因为它在我实现它时才开始这样做,但我不知道如何如何解决它。

//...

#define NUMBER_THREADS 8 //should be above 0
std::mutex nodelistaccessmutex;
std::condition_variable worktobedone;

//...

int main(int argc, char* argv[])
{


    //...

    //create threads for USE_LIST_THREAD and NUMBER_THREADS

    std::thread nodeForceCalculatorThreads[NUMBER_THREADS];
    std::stack<Node*> nodeStack;
    if (USE_LIST_THREAD) {
        for (int i = 0; i < NUMBER_THREADS; i++) {
            nodeForceCalculatorThreads[i] = std::thread(threadPool, nodeStack);
        }
    }
    for(int i = 60; i > 0; i--){
        OrderedZListForceCalculationWithThreads(node_list, current - previous, nodeStack);
    }

    std::cout << "done" << current - begin << std::endl;

    if (USE_LIST_THREAD) {
        for (int i = 0; i < NUMBER_THREADS; i++) {
            nodeForceCalculatorThreads[i].join();
        }
    }
    getchar();
    return 0;
}

//...


//function that I think is causing the problem:

void threadPool(std::stack<Node*> nodeStack) {
    std::unique_lock<std::mutex> lk(nodelistaccessmutex);
    while (true) {
        nodelistaccessmutex.lock(); //lock or lock guard? notify one or all

        worktobedone.wait(lk, [nodeStack] {return nodeStack.empty();});
        std::cout << ".";

        //do actual work here
        //nodelistaccessmutex.unlock();

    }
    return;
}

//...

void OrderedZListForceCalculationWithThreads(std::list<Node*> node_list, double i_interval, std::stack<Node*> nodeStack) {
    //std::cout << ".";
    double x, y, z, x1, y1, z1, x2, y2, z2, distance, force;

    if (i_interval <= 0) {
        return;
    }

    for (auto& node_i : node_list) {
        nodeStack.push(node_i);
        worktobedone.notify_all();
    }
}

0 个答案:

没有答案