- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在开始使用 C 中的 pthreads,我也是一个疯狂的人,我尽可能地把我的代码写成“无错误”。
尽管试图格外小心,但 valgrind 告诉我,无论天气如何,我都在泄漏内存:
我知道这已经被讨论过(参见 this 、 this 和 this ),但我仍然很好奇:
正如我从之前的答案和 valgrind 跟踪中了解到的那样,pthread_create() 是根本原因,根据需要扩展线程使用的堆栈并有时重用它,因此缺少一些释放。但不太清楚的是为什么它取决于执行运行以及为什么它也会在创建分离线程时发生。正如我从某些答案、评论以及该人那里看到的那样,线程完成后将释放分离线程的资源。我已经尝试了各种调整来解决这个问题(在每个线程结束之前添加一个 sleep 时间,在主线程结束之前,增加堆栈大小,添加更多“工作”......)但它并没有改变最终结果差了很多。另外,为什么在处理分离线程时整体“mallocs()”的数量是随机的,valgrind 是否会丢失一些分离线程?这似乎也不取决于堆栈大小。
所提供的代码是一个经理/ worker 模型的模拟示例,恕我直言,线程管理的 joinable/join() 方法似乎更适合。
感谢您提供的任何启发!我也希望这些(过度评论的)代码片段对任何希望开始使用 pthreads 的人有所帮助。
- 交换
PS 系统信息:debian 64 位 arch 上的 gcc
代码片段 1(已加入可加入的线程):
/* Running this multiple times with valgrind, I sometimes end with :
- no errors (proper malloc/free balance)
- 4 extra malloc vs free (most frequently)
The number of mallocs() is more conservative and depends on the number of threads.
*/
#include <stdlib.h> /* EXIT_FAILURE, EXIT_SUCCESS macros & the likes */
#include <stdio.h> /* printf() & the likes */
#include <pthread.h> /* test subject */
#define MAX_THREADS 100 /* Number of threads */
pthread_attr_t tattr; /* Thread attribute */
pthread_t workers[MAX_THREADS]; /* All the threads spawned by the main() thread */
/* A mock container structure to pass arguments around */
struct args_for_job_t {
int tid;
int status;
};
/* The job each worker will perform upon creation */
void *job(void *arg)
{
/* Cast arguments in a proper container */
struct args_for_job_t *container;
container = (struct args_for_job_t *)arg;
/* A mock job */
printf("[TID - %d]\n", container->tid);
/* Properly exit with status code tid */
pthread_exit((void *)(&container->status));
}
int main ()
{
int return_code; /* Will hold return codes */
void *return_status; /* Will hold return status */
int tid; /* Thread id */
struct args_for_job_t args[MAX_THREADS]; /* For thread safeness */
/* Initialize and set thread joinable attribute */
pthread_attr_init(&tattr);
pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_JOINABLE);
/* Spawn detached threads */
for (tid = 0; tid < MAX_THREADS; tid++)
{
args[tid].tid = tid;
args[tid].status = tid;
return_code = pthread_create(&workers[tid], &tattr, job, (void *)(&args[tid]));
if (return_code != 0) { printf("[ERROR] Thread creation failed\n"); return EXIT_FAILURE; }
}
/* Free thread attribute */
pthread_attr_destroy(&tattr);
/* Properly join() all workers before completion */
for(tid = 0; tid < MAX_THREADS; tid++)
{
return_code = pthread_join(workers[tid], &return_status);
if (return_code != 0)
{
printf("[ERROR] Return code from pthread_join() is %d\n", return_code);
return EXIT_FAILURE;
}
printf("Thread %d joined with return status %d\n", tid, *(int *)return_status);
}
return EXIT_SUCCESS;
}
代码片段 2(创建后分离的线程):
/* Running this multiple times with valgrind, I sometimes end with :
- no errors (proper malloc/free balance)
- 1 extra malloc vs free (most frequently)
Most surprisingly, it seems there is a random amount of overall mallocs
*/
#include <stdlib.h> /* EXIT_FAILURE, EXIT_SUCCESS macros & the likes */
#include <stdio.h> /* printf() & the likes */
#include <pthread.h> /* test subject */
#include <unistd.h>
#define MAX_THREADS 100 /* Number of threads */
pthread_attr_t tattr; /* Thread attribute */
pthread_t workers[MAX_THREADS]; /* All the threads spawned by the main() thread */
/* A mock container structure to pass arguments around */
struct args_for_job_t {
int tid;
};
/* The job each worker will perform upon creation */
void *job(void *arg)
{
/* Cast arguments in a proper container */
struct args_for_job_t *container;
container = (struct args_for_job_t *)arg;
/* A mock job */
printf("[TID - %d]\n", container->tid);
/* For the sake of returning something, not necessary */
return NULL;
}
int main ()
{
int return_code; /* Will hold return codes */
int tid; /* Thread id */
struct args_for_job_t args[MAX_THREADS]; /* For thread safeness */
/* Initialize and set thread joinable attribute */
pthread_attr_init(&tattr);
pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_JOINABLE);
/* Spawn detached threads */
for (tid = 0; tid < MAX_THREADS; tid++)
{
args[tid].tid = tid;
return_code = pthread_create(&workers[tid], &tattr, job, (void *)(&args[tid]));
if (return_code != 0) { printf("[ERROR] Thread creation failed\n"); return EXIT_FAILURE; }
/* Detach worker after creation */
pthread_detach(workers[tid]);
}
/* Free thread attribute */
pthread_attr_destroy(&tattr);
/* Delay main() completion until all detached threads finish their jobs. */
usleep(100000);
return EXIT_SUCCESS;
}
代码片段 3(创建时分离的线程):
/* Running this multiple times with valgrind, I sometimes end with :
- no errors (proper malloc/free balance)
- 1 extra malloc vs free (most frequently)
Most surprisingly, it seems there is a random amount of overall mallocs
*/
#include <stdlib.h> /* EXIT_FAILURE, EXIT_SUCCESS macros & the likes */
#include <stdio.h> /* printf() & the likes */
#include <pthread.h> /* test subject */
#define MAX_THREADS 100 /* Number of threads */
pthread_attr_t tattr; /* Thread attribute */
pthread_t workers[MAX_THREADS]; /* All the threads spawned by the main() thread */
/* A mock container structure to pass arguments around */
struct args_for_job_t {
int tid;
};
/* The job each worker will perform upon creation */
void *job(void *arg)
{
/* Cast arguments in a proper container */
struct args_for_job_t *container;
container = (struct args_for_job_t *)arg;
/* A mock job */
printf("[TID - %d]\n", container->tid);
/* For the sake of returning something, not necessary */
return NULL;
}
int main ()
{
int return_code; /* Will hold return codes */
int tid; /* Thread id */
struct args_for_job_t args[MAX_THREADS]; /* For thread safeness */
/* Initialize and set thread detached attribute */
pthread_attr_init(&tattr);
pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);
/* Spawn detached threads */
for (tid = 0; tid < MAX_THREADS; tid++)
{
args[tid].tid = tid;
return_code = pthread_create(&workers[tid], &tattr, job, (void *)(&args[tid]));
if (return_code != 0) { printf("[ERROR] Thread creation failed\n"); return EXIT_FAILURE; }
}
/* Free thread attribute */
pthread_attr_destroy(&tattr);
/* Delay main() completion until all detached threads finish their jobs. */
usleep(100000);
return EXIT_SUCCESS;
}
代码片段 1 的 Valgrind 输出(加入的线程和内存泄漏)
==27802==
==27802== HEAP SUMMARY:
==27802== in use at exit: 1,558 bytes in 4 blocks
==27802== total heap usage: 105 allocs, 101 frees, 28,814 bytes allocated
==27802==
==27802== Searching for pointers to 4 not-freed blocks
==27802== Checked 104,360 bytes
==27802==
==27802== 36 bytes in 1 blocks are still reachable in loss record 1 of 4
==27802== at 0x4C2B6CD: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==27802== by 0x400894D: _dl_map_object (dl-load.c:162)
==27802== by 0x401384A: dl_open_worker (dl-open.c:225)
==27802== by 0x400F175: _dl_catch_error (dl-error.c:178)
==27802== by 0x4013319: _dl_open (dl-open.c:639)
==27802== by 0x517F601: do_dlopen (dl-libc.c:89)
==27802== by 0x400F175: _dl_catch_error (dl-error.c:178)
==27802== by 0x517F6C3: __libc_dlopen_mode (dl-libc.c:48)
==27802== by 0x4E423BB: pthread_cancel_init (unwind-forcedunwind.c:53)
==27802== by 0x4E4257B: _Unwind_ForcedUnwind (unwind-forcedunwind.c:130)
==27802== by 0x4E4069F: __pthread_unwind (unwind.c:130)
==27802== by 0x4E3AFF4: pthread_exit (pthreadP.h:265)
==27802==
==27802== 36 bytes in 1 blocks are still reachable in loss record 2 of 4
==27802== at 0x4C2B6CD: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==27802== by 0x400B7EC: _dl_new_object (dl-object.c:161)
==27802== by 0x4006805: _dl_map_object_from_fd (dl-load.c:1051)
==27802== by 0x4008699: _dl_map_object (dl-load.c:2568)
==27802== by 0x401384A: dl_open_worker (dl-open.c:225)
==27802== by 0x400F175: _dl_catch_error (dl-error.c:178)
==27802== by 0x4013319: _dl_open (dl-open.c:639)
==27802== by 0x517F601: do_dlopen (dl-libc.c:89)
==27802== by 0x400F175: _dl_catch_error (dl-error.c:178)
==27802== by 0x517F6C3: __libc_dlopen_mode (dl-libc.c:48)
==27802== by 0x4E423BB: pthread_cancel_init (unwind-forcedunwind.c:53)
==27802== by 0x4E4257B: _Unwind_ForcedUnwind (unwind-forcedunwind.c:130)
==27802==
==27802== 312 bytes in 1 blocks are still reachable in loss record 3 of 4
==27802== at 0x4C29DB4: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==27802== by 0x4010B59: _dl_check_map_versions (dl-version.c:300)
==27802== by 0x4013E1F: dl_open_worker (dl-open.c:268)
==27802== by 0x400F175: _dl_catch_error (dl-error.c:178)
==27802== by 0x4013319: _dl_open (dl-open.c:639)
==27802== by 0x517F601: do_dlopen (dl-libc.c:89)
==27802== by 0x400F175: _dl_catch_error (dl-error.c:178)
==27802== by 0x517F6C3: __libc_dlopen_mode (dl-libc.c:48)
==27802== by 0x4E423BB: pthread_cancel_init (unwind-forcedunwind.c:53)
==27802== by 0x4E4257B: _Unwind_ForcedUnwind (unwind-forcedunwind.c:130)
==27802== by 0x4E4069F: __pthread_unwind (unwind.c:130)
==27802== by 0x4E3AFF4: pthread_exit (pthreadP.h:265)
==27802==
==27802== 1,174 bytes in 1 blocks are still reachable in loss record 4 of 4
==27802== at 0x4C29DB4: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==27802== by 0x400B57D: _dl_new_object (dl-object.c:77)
==27802== by 0x4006805: _dl_map_object_from_fd (dl-load.c:1051)
==27802== by 0x4008699: _dl_map_object (dl-load.c:2568)
==27802== by 0x401384A: dl_open_worker (dl-open.c:225)
==27802== by 0x400F175: _dl_catch_error (dl-error.c:178)
==27802== by 0x4013319: _dl_open (dl-open.c:639)
==27802== by 0x517F601: do_dlopen (dl-libc.c:89)
==27802== by 0x400F175: _dl_catch_error (dl-error.c:178)
==27802== by 0x517F6C3: __libc_dlopen_mode (dl-libc.c:48)
==27802== by 0x4E423BB: pthread_cancel_init (unwind-forcedunwind.c:53)
==27802== by 0x4E4257B: _Unwind_ForcedUnwind (unwind-forcedunwind.c:130)
==27802==
==27802== LEAK SUMMARY:
==27802== definitely lost: 0 bytes in 0 blocks
==27802== indirectly lost: 0 bytes in 0 blocks
==27802== possibly lost: 0 bytes in 0 blocks
==27802== still reachable: 1,558 bytes in 4 blocks
==27802== suppressed: 0 bytes in 0 blocks
==27802==
==27802== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
--27802--
--27802-- used_suppression: 2 dl-hack3-cond-1
==27802==
==27802== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
代码片段 1 的 Valgrind 输出(没有内存泄漏,稍后运行几次)
--29170-- Discarding syms at 0x64168d0-0x6426198 in /lib/x86_64-linux-gnu/libgcc_s.so.1 due to munmap()
==29170==
==29170== HEAP SUMMARY:
==29170== in use at exit: 0 bytes in 0 blocks
==29170== total heap usage: 105 allocs, 105 frees, 28,814 bytes allocated
==29170==
==29170== All heap blocks were freed -- no leaks are possible
==29170==
==29170== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
--29170--
--29170-- used_suppression: 2 dl-hack3-cond-1
==29170==
==29170== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
最佳答案
当你的线程被分离时,你有一个错误,导致未定义的行为。
在 main 中你有这行代码:
struct args_for_job_t args[MAX_THREADS];
您将指针交给您的工作线程。
然后main()就到了这部分
pthread_exit(NULL);
并且 main() 不再存在,但您仍然可能有工作线程,它访问上面的 args
数组,该数组位于 main() 的堆栈上 - 它不再存在。在某些运行中,您的工作线程可能会在 main() 结束之前全部完成,但在其他运行中则不会。
关于c pthreads + valgrind = 内存泄漏 : why?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15207762/
我正在将一些 pthreads 代码添加到我使用 autotools 构建的 Linux 应用程序中。我收到关于未在 libpthreads 中链接的错误。所以我想在 autotools 中指定 pt
libpthread 库位于 Linux 系统的哪个目录中? 最佳答案 有多种方法可以找出这一点。 只需输入 find / -name 'libpthread.so' -print找到名为 libpt
pthread 属性对象是否需要在使用它们的对象的生命周期内存在,或者在使用它们后立即销毁它们是否安全?例如: // Create the mutex attributes. pthread_mute
到目前为止我读过的所有文档似乎都表明我的 vxWorks (6.8) 版本中存在 posix 线程支持,但是一个简单的测试应用程序无法按预期执行。来源如下: tTest.h #include cla
我试图找到指定 pthreads 标准的文档。我见过各种指向 IEEE 1003.1c-1995 的链接(即 Wikipedia 或 OpenGroup )。然而,当我在 IEEE 标准站点上搜索此文
我试图找到指定 pthreads 标准的文档。我见过各种指向 IEEE 1003.1c-1995 的链接(即 Wikipedia 或 OpenGroup )。然而,当我在 IEEE 标准站点上搜索此文
我在 MSVC 2010 上运行一个 pthread,我已经包含 pthreadVC2 .lib & .dll。来自以下网站 http://sourceware.org/pthreads-win32/
我的问题是: 如何在不更改其他 pthread 中的当前目录的情况下更改 pthread 中的当前目录,我找到了一个使用 openat() 函数的解决方案,但我没有找到任何解释它如何工作的示例。 使用
是否可以通过任何方式更改进程可以创建的 pthread 数量限制? 目前在我的 linux 系统上我可以创建大约 380 个线程,但我想增加它,只要内存可用。 最佳答案 减少用户的堆栈大小' ulim
问候。我正在尝试创建一个 autoconf 配置脚本,该脚本自动检查要使用的 pthread 选项,并且理想情况下,在使用 gcc 编译时指定 -pthread。 我希望 AX_PTHREAD 能够工
如何知道 pthread 是否死亡? 有办法检查 pthread 状态吗? 最佳答案 if(pthread_kill(the_thread, 0) == 0) { /* still runni
我正在从一个由互斥锁控制的固定大小的全局池中分配我的 pthread 线程特定数据。 (有问题的代码不允许动态分配内存;它允许使用的所有内存都由调用者作为单个缓冲区提供。pthreads 可能会分配内
在阅读了一些 MPI 规范后,我了解到,当使用 MPI_THREAD_SERIALIZED 进行初始化时,程序必须确保发生在不同线程中的 MPI_Send/Recv 调用不能重叠。换句话说,您需要一个
我尝试根据 this guide 安装 pthread win32 . 我将 pthreadVC2.dll 文件添加到 C:\Windows 并将 pthreadVC2.lib 文件添加到 C:\Pr
我有一个 pthreads 程序。我必须使用 Linux 中的 gcc -pthread(-pthreads 是无法识别的选项)和 Sun 中的 gcc -pthreads(-pthread 是无法识
我有一个包含文件名列表的文件,我想在其中搜索一个词并替换它我稍微修改了代码只是为了在这里只显示相关部分问题是如果我在该列表中只有一个文件,它不会用多线程处理它,因为线程只有在我有多个文件时才工作所以我
我正在编写一个 SMT 程序,并且正在尝试解决一个有趣的问题。 我需要所有函数一起退出,但是有些线程卡在障碍物上,即使我不希望它们这样做。 我的问题是:当我删除障碍时会发生什么?卡在屏障处的线程会释放
我阅读了有关 pthread 及其相关 API 的所有内容,以创建、锁定和同步不同的线程。但我经常发现线程池、消费者/生产者等词提示。我理解这些是 pthread 实现的模型。 任何人都可以让我知道
我在 man pthread_join 中读到,多个 pthread 不能加入一个已经加入的 pthread。还有另一种方法可以达到相同的结果吗?多个 pthread 挂起自己,直到某个特定的 pth
我知道 OpenMP 实际上只是一组编译成 pthread 的宏。有没有办法在编译的其余部分发生之前查看 pthread 代码?我正在使用 GCC 进行编译。 最佳答案 首先,OpenMP 不是一组简
我是一名优秀的程序员,十分优秀!