c++线程类中的错误,导致它在退出时消耗100%的CPU
Bug in C++ thread class that causes it to consume 100% CPU on exit
我有以下c++线程类,所有新的线程实例都是作为继承Thread
的类的对象实现的。要启动一个线程,首先创建一个对象,然后在该对象上调用run()
。我面临的问题是,一个线程的CPU使用率上升到100%后,thread_main
函数退出。因此,例如,如果一个对象要扩展这个类,并且它的thread_main只是一个printf ( "%s", "Hello World" ); return ;
,那么启动一个线程将导致多核处理器上的CPU使用率跃升100%。我做错了什么?
class Thread {
public:
Thread ( )
{
}
virtual ~Thread ( ) {}
/// function to be called after construction to start thread
void run ( )
{
pthread_create ( &pthread_obj_, NULL, &(static_start_routine), this );
}
/// called by the thread that has created this thread when it has nothing to do
/// apart from waiting for this thread to exit
void stop ( )
{
pthread_join ( pthread_obj_, NULL );
}
protected:
/// implement this function in child class. This is sort of the main
/// point of control for Thread class and derived classes.
/// Exiting this function means the thread is closed
virtual void thread_main ( ) = 0;
private:
pthread_t pthread_obj_;
/// The function supplied as argument to pthread_create must be a static function
/// and hence the real start of the thread is Thread::thread_main
static void * static_start_routine ( void * p_thread_subclass_object_ )
{
reinterpret_cast < Thread * >(p_thread_subclass_object_)->thread_main ( );
return NULL;
}
};
class ClientThread : public Thread
{
public:
ClientThread ( DebugLogger & r_dbglogger_, const int r_client_id_, const int r_fd_ )
: ( dbglogger_ ( r_dbglogger_ ), client_id_ ( r_client_id_ ), fd_ ( r_fd_ )
{}
virtual ~ClientThread ( ) {}
void thread_main ( )
{
GenericORSRequestStruct t_client_request_;
int retval = read ( fd_, & t_client_request_, sizeof ( GenericORSRequestStruct ) ) ;
// processing code
}
private:
DebugLogger & dbglogger_;
const int client_id_;
const int fd_;
};
// relevant part from "accept" thread
void ClientReceiver::thread_main ( )
{
while ( int fd_ = tcp_server_socket_.Accept ( ) )
{
client_id_ ++;
ClientThread * t_client_thread_ = new CleintThread ( dbglogger_, client_id_, fd_ ) ;
t_client_thread_->run ( ); // starts the thread
}
}
// so Thread::stop() is not being called anywhere.
几个建议…
- 确保链接到线程安全版本的C/c++运行库(visa-vi printf)。
- 还要确保等待新线程,而不是让main()返回,直到线程实际完成执行。在main()之后调用printf()可能会有问题。
- 确保线程对象在
stop()
之前实际上是活的(例如,没有被父线程删除)。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 创建LinkedList退出,返回代码为-11(SIGSEGV)
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 如何让LLDB在成功时退出,在失败时等待
- C++控制台应用程序阻止退出
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 程序在执行程序的其余部分之前退出
- 构造函数在退出函数时无法初始化一个参数
- 为什么异常不退出程序?
- 我不断收到 [错误] ID 返回 1 退出状态错误,但看不到问题所在
- 退出简单while循环时出现问题
- 使用vscode调试时,GDB意外退出
- 有哪些有效的方法可以消除一组 100 万个字符串>重复数据?
- pclose() 不会给我进程退出代码
- 为什么系统函数总是在C++中返回已转移的退出状态?
- C++从另一个函数退出函数
- C++ 中的编译错误:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- C++逗号分隔的输入数组代码过早退出
- Netbeans 10:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)
- c++线程类中的错误,导致它在退出时消耗100%的CPU