大家好,我只发布代码的核心,这些代码创建了problemam,并且可以使用线程。
#define HR_OFF h_r-1
pthread_t *threads = NULL;
int h_r = 1;
int foo(int handler)
{
// if everything is empty alloc resources
if (threads == NULL) {
threads = (pthread_t*)malloc(sizeof(pthread_t));
// stuff with other variables
h_r++;
}
else {
// stuff with other variables
threads = (pthread_t*)realloc(threads, sizeof(pthread_t) * h_r);
h_r++;
}
// stuff with other variables
register unsigned int counter = 0;
while (pthread_create(&threads[HR_OFF], NULL, (void*)&foo2, NULL) != 0) {
if (counter == MAX_TRYING) {
fprintf(stderr, "THREAD_ERROR_C occurs \n");
return THREAD_ERROR_C;
}
}
return 0;
}
int foo2(void *data)
{
// stuff with other variables
}
我们可以看到foo函数创建新线程并重新分配内存来存储pthread_t。然后它尝试创建一个新的线程,其中pthread_create为NULL作为attr和arg,并作为函数指针创建指向foo2的指针;
现在的问题是,当我执行代码时,当调用pthread_create时会出现内存分配错误,从而产生此错误消息:
Program received signal SIGABRT, Aborted.
__GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:51
../sysdeps/unix/sysv/linux/raise.c: File o directory non esistente.
如果使用gdb进行打印回溯
#0 __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:51
#1 0x00007ffff78513fa in __GI_abort () at abort.c:89
#2 0x00007ffff78939c8 in __malloc_assert (
assertion=assertion@entry=0x7ffff7983088 "(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)", file=file@entry=0x7ffff797f867 "malloc.c", line=line@entry=2406, function=function@entry=0x7ffff79838d0 <__func__.11275> "sysmalloc") at malloc.c:301
#3 0x00007ffff7895546 in sysmalloc (nb=nb@entry=288, av=0x7ffff7bb6b00 <main_arena>) at malloc.c:2403
#4 0x00007ffff789642d in _int_malloc (av=av@entry=0x7ffff7bb6b00 <main_arena>, bytes=bytes@entry=272) at malloc.c:3865
#5 0x00007ffff7898b4b in __libc_calloc (n=<optimized out>, elem_size=<optimized out>) at malloc.c:3274
#6 0x00007ffff7deaf42 in allocate_dtv (result=result@entry=0x7ffff781c700) at dl-tls.c:322
#7 0x00007ffff7deb8ce in __GI__dl_allocate_tls (mem=mem@entry=0x7ffff781c700) at dl-tls.c:539
#8 0x00007ffff7bc400c in allocate_stack (stack=<synthetic pointer>, pdp=<synthetic pointer>, attr=0x7fffffffe4b0) at allocatestack.c:580
---Type <return> to continue, or q <return> to quit---
#9 __pthread_create_2_1 (newthread=0x55555575b4c8, attr=<optimized out>, start_routine=0x5555555564fd <pthread_fetcher_function>, arg=0x0) at pthread_create.c:539
我如何解决这个问题,问题出在哪里。
感谢所有人的耐心和对不起我的英语
答案 0 :(得分:5)
您的线程分配代码毫无意义,因为您只有1个线程句柄并且访问它threads[HR_OFF]
可能超出范围。转换(void) * &foo2
也是错误的,因为foo2
具有适当的签名。还在循环内重试失败的线程创建也不是一个好主意。请注意,此循环实际上是无限的,因为您永远不会增加counter
。在决定重试之前,您至少应该检查失败原因。