use*_*210 1 c++ memory pthreads
我的程序因检测到堆栈粉碎而失败,我从 Valgring 收到的唯一消息是“块可能在丢失记录中丢失”重复了三遍,我不知道如何解决。
==3726== 144 bytes in 1 blocks are possibly lost in loss record 74 of 87
==3726== at 0x4025315: calloc (vg_replace_malloc.c:467)
==3726== by 0x4010CD7: allocate_dtv (dl-tls.c:300)
==3726== by 0x401146B: _dl_allocate_tls (dl-tls.c:464)
==3726== by 0x40405C6: pthread_create@@GLIBC_2.1 (allocatestack.c:570)
==3726== by 0x806BF36: Thread::Thread(void* (*)(void*), void*) (os.cpp:203)
Run Code Online (Sandbox Code Playgroud)
这是代码,Valgrind 是 pthread_create 调用。
Thread::Thread( PFUNC func, void * arg )
{
int s = pthread_create( &_ThreadId, NULL, func, arg); //here is msg from valgrind
if (s != 0)
throw EXCEPT_NOTHREAD;
pthread_detach( _ThreadId );
}
Run Code Online (Sandbox Code Playgroud)
请你帮我看看 Thread 函数有什么问题吗?我在其他类似的问题中读到 pthread_detach 必须在创建线程之前?预先非常感谢。
请你帮我看看 Thread 函数有什么问题吗?
本身并没有什么“错误”。它只是在程序结束之前没有释放线程的资源,Valgrind 将此报告为内存泄漏。由于您已经分离了线程,因此在线程终止之前不会释放其资源。如果它没有在程序之前终止,那么它们可能会被报告为泄漏。
我在其他类似的问题中读到 pthread_detach 必须在创建线程之前?
你不需要使用pthread_detach; 它用于使线程负责释放自己的资源。如果您不使用它,那么pthread_join当需要停止线程时,另一个线程将需要调用。
如果您想清理泄漏,那么您必须保留线程句柄,而不是分离线程(我猜您已经在这样做,假设_ThreadId是一个成员变量)。然后,在程序结束之前,告诉线程停止,然后调用pthread_join等待它并释放其所有资源。是否值得这样做来删除(可能无害的)警告取决于您,但干净的关闭可能有助于避免更严重的潜在问题。
顺便说一句,您不应该使用_ThreadId以 a 开头_,后跟大写字母的名称;像这样的名字是保留的。