[PD-dev] pd external memory weirdness

tim redfern pd at eclectronics.org
Thu Apr 17 11:25:39 CEST 2008


Hi Claude,

> 
> stest disappears when the thread_bang() returns, the thread is still 
> running, and maybe pthread internals write to stest after it is no 
> longer there, which would be very bad:  at best, a segmentation fault, 
> at worst, no crash but wrong behaviour.
> 
> At a guess: malloc() a list node with the pthread_t in it, and store 
> those nodes in a list in the Pd object struct.

I see what you mean, I don't think this is it though as:

-- its not crashing or giving errors (just leaking memory: memory which
isn't even owned by the new thread)

-- pthreads aren't 'owned' by the code that calls them: a thread can
exist even after the thread that calls it terminates. surely in this
case the pointer to the thread must have been freed first.

-- I'm using the same method as in this well known tutorial on pthreads:
https://computing.llnl.gov/tutorials/pthreads/#CreatingThreads

-- I've tried your suggestion of moving the pthread pointer to the scope
of the external structure and it doesn't help: see even more simple
example code below.

Can anyone else think of a reason why opening a new thread inside pd
would confuse malloc like this? Or can anyone else verify that this code
causes a leak (just to prove that I'm not going crazy!)

Thanks, Tim


--------The code

#include "m_pd.h"
#include <stdlib.h>
#include <pthread.h>

static t_class *thread_class;

typedef struct _thread {
  t_object  x_obj;
  pthread_t stest;
} t_thread;

void *threadtester( void* x_obj  ) {
	t_thread *x= (t_thread *) x_obj;
	
	//do nothing in particular

	return 0;
}

void thread_bang(t_thread *x)
{
	char* temp=(char*)malloc(1000000);
	free(temp);
	
	pthread_create (&x->stest,NULL,threadtester,(void *) x);
	post("hello world!");
}

void *thread_new(void)
{
  t_thread *x = (t_thread *)pd_new(thread_class);

  return (void *)x;
}

void thread_setup(void) {
	thread_class = class_new(gensym("thread"),
		(t_newmethod)thread_new,
		0, sizeof(t_thread),
		CLASS_DEFAULT, 0);
	class_addbang(thread_class, thread_bang);
}






More information about the Pd-dev mailing list