多线程的分段错误
由于该等式末尾的 free(),我遇到错误分段错误...
我不需要释放临时变量 *stck 吗?或者因为它是本地指针并且 从未通过 malloc 分配过内存空间,编译器会为我清理它吗?
void * push(void * _stck)
{
stack * stck = (stack*)_stck;//temp stack
int task_per_thread = 0; //number of push per thread
pthread_mutex_lock(stck->mutex);
while(stck->head == MAX_STACK -1 )
{
pthread_cond_wait(stck->has_space,stck->mutex);
}
while(task_per_thread <= (MAX_STACK/MAX_THREADS)&&
(stck->head < MAX_STACK) &&
(stck->item < MAX_STACK)//this is the amount of pushes
//we want to execute
)
{ //store actual value into stack
stck->list[stck->head]=stck->item+1;
stck->head = stck->head + 1;
stck->item = stck->item + 1;
task_per_thread = task_per_thread+1;
}
pthread_mutex_unlock(stck->mutex);
pthread_cond_signal(stck->has_element);
free(stck);
return NULL;
}
I get error segmentation fault because of the free() at the end of this equation...
don't I have to free the temporary variable *stck? Or since it's a local pointer and
was never assigned a memory space via malloc, the compiler cleans it up for me?
void * push(void * _stck)
{
stack * stck = (stack*)_stck;//temp stack
int task_per_thread = 0; //number of push per thread
pthread_mutex_lock(stck->mutex);
while(stck->head == MAX_STACK -1 )
{
pthread_cond_wait(stck->has_space,stck->mutex);
}
while(task_per_thread <= (MAX_STACK/MAX_THREADS)&&
(stck->head < MAX_STACK) &&
(stck->item < MAX_STACK)//this is the amount of pushes
//we want to execute
)
{ //store actual value into stack
stck->list[stck->head]=stck->item+1;
stck->head = stck->head + 1;
stck->item = stck->item + 1;
task_per_thread = task_per_thread+1;
}
pthread_mutex_unlock(stck->mutex);
pthread_cond_signal(stck->has_element);
free(stck);
return NULL;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编辑:您完全改变了问题,所以我的旧答案不再有意义了。我将尝试回答新问题(旧答案仍在下面),但作为参考,下次请只提出一个新问题,而不是更改旧问题。
stck
是一个指针,您将其设置为指向与_stck
指向的同一内存。指针并不意味着分配内存,它只是指向已经(希望)分配的内存。例如,当您这样做时,您会释放相同的内存两次。
-- 旧答案
在推送中,您将
stck
设置为指向与_stck
相同的内存块,并在调用结束时你释放堆栈(从而从每个线程在公共堆栈上调用一次 free() )删除
free()
调用,至少对我来说,它不会再崩溃了。加入所有线程后,释放堆栈可能应该在main()
中完成。Edit: You totally changed the question so my old answer doesn't really make sense anymore. I'll try to answer the new one (old answer still below) but for reference, next time please just ask a new question instead of changing an old one.
stck
is a pointer that you set to point to the same memory as_stck
points to. A pointer does not imply allocating memory, it just points to memory that is already (hopefully) allocated. When you do for exampleyou free the same memory twice.
-- old answer
In push, you're setting
stck
to point to the same memory block as_stck
, and at the end of the call you free stack (thereby calling free() on your common stack once from each thread)Remove the
free()
call and, at least for me, it does not crash anymore. Deallocating the stack should probably be done inmain()
after joining all the threads.