c++ 11线程不连接
C++11 Threads Not Joining
我有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("%sn", *in_c);
}
int main(int argc, const char * argv[]) {
ThreadPool pool;
const char* test_c = "hello_world";
pool.execute([&]() { print(&test_c, nullptr); });
}
它的输出是:
hello_world
Stopping 0
之后,主线程停止,因为它正在等待第一个线程加入(在ThreadPool的析构函数中)。由于某些原因,worker的m_running
变量没有设置为false,从而使应用程序无限期地运行。
在Worker::stop
中,成员m_running
在主线程中写入,而在另一个线程中读取。这是未定义的行为。您需要保护来自不同线程的读/写访问。在这种情况下,我建议使用std::atomic<bool>
代替m_running
。
编辑:同样适用于m_hasData
.
相关文章:
- 为什么我的 std::atomic<int> 变量不是线程安全的?
- 在不减慢线程速度的情况下保存大量数据
- OMP 不启动线程
- gdb:在多线程程序中调用函数,不进行线程
- 为什么消息框不阻止线程?
- 如何在不冻结线程/应用程序的情况下减慢方法执行速度
- 为什么它不是线程安全以及如何获得线程安全?
- 为什么链表不是线程安全的?
- 为什么std::queue不是线程安全的
- Boost::类中的Mutex不是线程安全的
- c ++ 为什么我的日期解析不是线程安全的
- 为什么不从线程调用重载成员
- 我们如何在不杀死线程的情况下重新初始化线程
- 当gemm做时,sgemm不多线程
- c++不能理解为什么这段代码不是线程安全的
- C++ - _beginthreadex() 不启动线程
- Boost ptime在MinGW下不是线程安全的
- 为什么将条件写转换为无条件写不是线程安全的优化?
- 是否有任何cpp函数或对象(不包括从c继承的)不是线程安全的,即使每个线程对自己的数据进行操作
- 本地静态指针变量不是线程安全的