mirror of
https://github.com/Hizenberg469/MultiThreading_Part_A.git
synced 2026-04-20 02:22:23 +03:00
pthread cleanup API
This commit is contained in:
@@ -1,5 +1,20 @@
|
||||
#include "master_slave.h"
|
||||
|
||||
void
|
||||
memory_cleanup_handler(void* arg) {
|
||||
|
||||
printf("%s invoked ...\n", __FUNCTION__);
|
||||
free(arg);
|
||||
}
|
||||
|
||||
void
|
||||
file_cleanup_handler(void* arg) {
|
||||
|
||||
printf("%s invoked ...\n", __FUNCTION__);
|
||||
fclose((FILE*)arg);
|
||||
|
||||
}
|
||||
|
||||
void *
|
||||
write_into_file(void* arg) {
|
||||
|
||||
@@ -14,15 +29,22 @@ write_into_file(void* arg) {
|
||||
/* Mode of cancellation */
|
||||
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0);
|
||||
int* thread_id = (int*)arg;
|
||||
|
||||
/* When pthread_cancel is invoked and this thread get the
|
||||
signal to get cancelled, this API is invoked to free up the
|
||||
resources used by this thread.*/
|
||||
pthread_cleanup_push(memory_cleanup_handler, arg);
|
||||
|
||||
sprintf(file_name, "thread_%d.txt", *thread_id);
|
||||
|
||||
FILE* fptr = fopen(file_name, "w");
|
||||
|
||||
pthread_cleanup_push(file_cleanup_handler, fptr);
|
||||
|
||||
if (!fptr) {
|
||||
printf("Error : Could not open log file %s, errno = %d\n",
|
||||
file_name, errno);
|
||||
return 0;
|
||||
pthread_exit(0);
|
||||
}
|
||||
|
||||
while (1) {
|
||||
@@ -32,6 +54,16 @@ write_into_file(void* arg) {
|
||||
sleep(1);
|
||||
}
|
||||
|
||||
fclose(fptr);
|
||||
/* If this thread is successfully executed and the cancellation request
|
||||
is not invoked till now then, the stack where resource free API are
|
||||
need to be cleaned.*/
|
||||
pthread_cleanup_pop(0);
|
||||
pthread_cleanup_pop(0);
|
||||
|
||||
/*This is not executed as this thread is in infinite loop
|
||||
and when the pthread_cancel is executed this thread is cancelled
|
||||
while it was executing in the loop. Hence, this causes resource
|
||||
leakage.*/
|
||||
// fclose(fptr);
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user