The reason it works with
sleep is because that pauses the execution of the calling function while the thread catches up. Without
sleep the
Start function exits before the thread assigns
ptr, making
temp no longer exist when the thread tries to use it via the handle (
Student& ptr = *(temp->ptr);.)
ta0kira
PS Because the stack unwinds after the return of
Start and
temp was the second item placed on its stack, it's likely already overwritten by the
sleep(14) call before the thread gets to it.
PPS If the
Student class creates the thread then it needs to store a
pthread_t as a class member. In the destructor, it either needs to
pthread_cancel or
pthread_wait so that the thread
is never running when the object no longer exists. The
sleep(14) mitigates this for you, but it's highly unrealistic because that defeats the purpose of a thread.
P^3S Some advice for your future in multi-threading (doesn't apply here, but can save you a headache):
Code:
//instead of:
int *my_int = new int;
delete my_int;
my_int = NULL;
Code:
//do this to prevent a gap (or exception) between 'delete' and '= NULL'
int *my_int = new int;
int *temp = my_int;
my_int = NULL;
delete temp;