I am using posix threads in C. I have two threads in my program, thread1 and thread2. thread1 starts thread2.
thread1 maintains a variable var1 based on which thread2 has to be exited safely.
thread2 calls many lengthy functions (whose runtime can be upto 5 sec). There are many memory allocations using malloc in thread2. As soon as var1 becomes true, I need to close thread2 but only after deallocating all allocated memories. How this can be done?
The code looks like this:
void * func1(void *arg)
{
pthread_create(&thread2, &attr, func2, NULL);
while(1)
{
// ...
var1 = func3();
if(var1 == true)
{
// Cancel thread2
}
// ...
}
}
void * func2(void *arg)
{
// ...
func4(); // runs for 2 sec
char* var2 = malloc(10);
func5(); // runs for 5 sec
char* var3 = malloc(20);
// ...
cleanup:
free(var2);
free(var3);
return (void*) 0;
}