52 lines
1.8 KiB
C
52 lines
1.8 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* forks_threads.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: erey-bet <marvin@42.fr> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2023/04/09 20:49:44 by erey-bet #+# #+# */
|
|
/* Updated: 2023/04/09 20:49:47 by erey-bet ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "philo.h"
|
|
|
|
void take_fork(t_philo *philo, int id_fork)
|
|
{
|
|
pthread_mutex_lock(&philo->same->mutex[id_fork]);
|
|
philo->same->forks[id_fork] = 0;
|
|
pthread_mutex_unlock(&philo->same->mutex[id_fork]);
|
|
}
|
|
|
|
void drop_fork(t_philo *philo, int id_fork, int next_id_fork)
|
|
{
|
|
pthread_mutex_lock(&philo->same->mutex[id_fork]);
|
|
philo->same->forks[id_fork] = 1;
|
|
pthread_mutex_unlock(&philo->same->mutex[id_fork]);
|
|
if (next_id_fork >= 0)
|
|
{
|
|
pthread_mutex_lock(&philo->same->mutex[next_id_fork]);
|
|
philo->same->forks[next_id_fork] = 1;
|
|
pthread_mutex_unlock(&philo->same->mutex[next_id_fork]);
|
|
}
|
|
}
|
|
|
|
int get_fork(t_philo *philo, int id_fork)
|
|
{
|
|
int fork;
|
|
|
|
pthread_mutex_lock(&philo->same->mutex[id_fork]);
|
|
fork = philo->same->forks[id_fork];
|
|
pthread_mutex_unlock(&philo->same->mutex[id_fork]);
|
|
usleep(10);
|
|
return (fork);
|
|
}
|
|
|
|
void ft_sleep(long long time_to_sleep)
|
|
{
|
|
if (time_to_sleep < 0)
|
|
return ;
|
|
usleep(time_to_sleep);
|
|
}
|