C++ 11线程没有加入

Rap*_*Cpp 2 c++ multithreading c++11

我有使用Java的线程的经验,但想学习如何在C++ 11中使用它们.我试图创建一个简单的线程池,其中线程被创建一次,可以被要求执行任务.

#include <thread>
#include <iostream>

#define NUM_THREADS 2

class Worker
{
public:
    Worker(): m_running(false), m_hasData(false)
    {

    };
    ~Worker() {};

    void execute()
    {
        m_running = true;

        while(m_running)
        {
            if(m_hasData)
            {
                m_system();
            }
            m_hasData = false;
        }
    };

    void stop()
    {
        m_running = false;
    };

    void setSystem(const std::function<void()>& system)
    {
        m_system = system;
        m_hasData = true;
    };

    bool isIdle() const
    {
        return !m_hasData;
    };
private:
    bool m_running;
    std::function<void()> m_system;
    bool m_hasData;
};

class ThreadPool
{
public:
    ThreadPool()
    {
        for(int i = 0; i < NUM_THREADS; ++i)
        {
            m_threads[i] = std::thread(&Worker::execute, &m_workers[i]);
        }
    };
    ~ThreadPool()
    {
        for(int i = 0; i < NUM_THREADS; ++i)
        {
            std::cout << "Stopping " << i << std::endl;
            m_workers[i].stop();
            m_threads[i].join();
        }
    };

    void execute(const std::function<void()>& system)
    {
        // Finds the first non-idle worker - not really great but just for testing
        for(int i = 0; i < NUM_THREADS; ++i)
        {
            if(m_workers[i].isIdle())
            {
                m_workers[i].setSystem(system);
                return;
            }
        }
    };
private:
    Worker m_workers[NUM_THREADS];
    std::thread m_threads[NUM_THREADS];
};

void print(void* in, void* out)
{
    char** in_c = (char**)in;
    printf("%s\n", *in_c);
}

int main(int argc, const char * argv[]) {
    ThreadPool pool;
    const char* test_c = "hello_world";
    pool.execute([&]() { print(&test_c, nullptr); });
}
Run Code Online (Sandbox Code Playgroud)

这个输出是:

hello_world
Stopping 0
Run Code Online (Sandbox Code Playgroud)

之后,主线程停止,因为它正在等待第一个线程加入(在ThreadPool的析构函数中).由于某种原因,m_runningworker 的变量未设置为false,这使应用程序无限期地运行.

小智 5

在Worker::stop成员m_running中写入主线程,而在不同的线程中执行读取.这是未定义的行为.您需要保护来自不同线程的读/写访问权限.在这种情况下,我会建议使用std::atomic<bool>的m_running.

编辑:同样适用m_hasData.