I’m into the Philosophers project, it is about handling threads and mutexes. For the project I need to create several threads, each thread runs a routine function and accesses shared resources. I discovered that when I test pthread_create() != 0 it causes a broad set of errors, from data race to segfault. When there is a thread error, I want to exit the loop, clean all resources and join created threads, but as they use mutexes I can not free locked values. I was thinking about using pthread_detach but not sure how to do it right.
#include "philo.h"
int create_threads(t_philo *data, t_program *set)
{
int i;
i = 0;
while (i < data->num_of_philos)
{
if (pthread_create(&set->philos[i].thread,
NULL, routine, &set->philos[i]))
{
ft_putstr_fd("Error thread create", 2);
cleanup_all(set);
return (0);
}
i++;
}
return (1);
}
int join_threads(t_philo *data, t_program *set)
{
int i;
i = 0;
while (i < data->num_of_philos)
{
if (pthread_join(set->philos[i].thread, NULL))
{
ft_putstr_fd("Error thread join", 2);
cleanup_all(set);
return (0);
}
i++;
}
return (1);
}
void cleanup_all(t_program *set)
{
int i;
i = 0;
while (i < set->philos[0].num_of_philos)
{
pthread_mutex_destroy(&set->forks[i]);
i++;
}
pthread_mutex_destroy(&set->meal_lock);
pthread_mutex_destroy(&set->dead_lock);
pthread_mutex_destroy(&set->write_lock);
free(set->forks);
free(set->philos);
}
I tried to modify cleanup function but it is not working as expected. And limits of my project I cant use exit()