I want to release a pthread virtual memory everytime it is ended and before a new thread is created. This is my simple program and i can only join and create, detach and cancel cannot function.


#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 3

void *BusyWork(void *null)
{
int i;
double result=0.0;
for (i=0; i<1000000; i++)
{
result = result + (double)random();
}
printf("Thread result = %e\n",result);
pthread_exit((void *) 0);
}

int main(int argc, char *argv[])
{
pthread_t thread[NUM_THREADS];
pthread_attr_t attr;
int rc, t;
int a;
int status;

/* Initialize and set thread detached attribute */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

while(t)
{
printf("Enter a detach number:");
scanf("%d",&a);

printf("Completed detach with thread %d status= %d\n",t, status);

switch(a){

case 1:
printf("1\n");
rc=pthread_create(&thread[0], &attr, BusyWork, NULL);
printf("create returns: %d\n",rc);
if(rc==0){printf("create success\n\n");}
else{printf("create failed\n\n");};
break;

case 2:
printf("2\n");
rc = pthread_join(thread[0], (void **)&status);
printf("join returns: %d\n",rc);
if(rc==0){printf("join success\n");}
else{printf("join failed\n\n");};
break;

case 3:
printf("3\n");
rc=pthread_cancel(thread[0]);
printf("cancel returns: %d\n",rc);
if(rc==0){printf("cancel success\n\n");}
else{printf("cancel failed\n\n");};
break;

case 4:
printf("4\n");
rc=pthread_detach(thread[0]);
printf("detach returns: %d\n",rc);
if(rc==0){printf("detach success\n\n");}
else{printf("detach failed\n\n");};
break;

case 5:
printf("5\n");
pthread_exit(NULL);

case 11:
printf("11\n");
rc=pthread_create(&thread[1], &attr, BusyWork, NULL);
printf("create returns: %d\n",rc);
if(rc==0){printf("create success\n\n");}
else{printf("create failed\n\n");};
break;

case 22:
printf("22\n");
rc = pthread_join(thread[1], (void **)&status);
printf("join returns: %d\n",rc);
if(rc==0){printf("join success\n");}
else{printf("join failed\n\n");};
break;

case 33:
printf("33\n");
rc=pthread_cancel(thread[1]);
printf("cancel returns: %d\n",rc);
if(rc==0){printf("cancel success\n\n");}
else{printf("cancel failed\n\n");};
break;

case 44:
printf("44\n");
rc=pthread_detach(thread[1]);
printf("detach returns: %d\n",rc);
if(rc==0){printf("detach success\n\n");}
else{printf("detach failed\n\n");};
break;

case 55:
printf("55\n");
pthread_exit(NULL);

default:

printf("else\n");
exit(0);

}


}

}



Please advise me. Thanks