tgrekov-philosophers
HIVE philosophers July 2024
Loading...
Searching...
No Matches
seat.c
Go to the documentation of this file.
1/* ************************************************************************** */
2/* */
3/* ::: :::::::: */
4/* seat.c :+: :+: :+: */
5/* +:+ +:+ +:+ */
6/* By: tgrekov <tgrekov@student.hive.fi> +#+ +:+ +#+ */
7/* +#+#+#+#+#+ +#+ */
8/* Created: 2024/08/02 07:20:21 by tgrekov #+# #+# */
9/* Updated: 2024/08/06 17:10:30 by tgrekov ### ########.fr */
10/* */
11/* ************************************************************************** */
12
20#include <stdlib.h>
21#include <unistd.h>
22#include "../philosopher/philo.h"
23
24int setup(t_global *global, t_thread **thread);
25void *breakfast(void *data);
26
34static void monitor_eat_quota(t_global *global, t_thread *thread, int i)
35{
36 usleep((global->opt.tt_eat + global->opt.tt_sleep)
37 * (global->opt.eat_n - 1) * 1000);
38 while (i--)
39 {
40 pthread_mutex_lock(&thread[i].full);
41 pthread_mutex_unlock(&thread[i].full);
42 pthread_mutex_destroy(&thread[i].full);
43 }
44 set_end(global);
45}
46
54static int create_threads(t_global *global, t_thread *thread)
55{
56 int i;
57 int res;
58
59 i = 0;
60 res = 0;
61 while (i < global->opt.n && !res)
62 {
63 thread[i].i = i;
64 thread[i++].global = global;
65 if (pthread_create(&thread[i - 1].thread, 0,
66 breakfast, (void *) &thread[i - 1]))
67 {
68 res = 1;
69 set_end(global);
70 break ;
71 }
72 }
73 if (global->opt.eat_n)
74 monitor_eat_quota(global, thread, i);
75 while (i--)
76 {
77 if (pthread_join(thread[i].thread, 0) || thread[i].err)
78 res = 1;
79 }
80 return (res);
81}
82
90int seat(t_opt opt)
91{
92 t_global global;
93 t_thread *thread;
94 int i;
95
96 global.end = 0;
97 global.opt = opt;
98 if (!setup(&global, &thread))
99 {
100 create_threads(&global, thread);
101 pthread_mutex_destroy(&global.printing);
102 pthread_mutex_destroy(&global.end_mutex);
103 i = 0;
104 while (i < opt.n)
105 pthread_mutex_destroy(&global.forks[i++]);
106 }
107 free(global.forks);
108 free(thread);
109 return (0);
110}
int err(const char *str, int retval)
Write str to stderr and return retval.
Definition err.c:29
static int create_threads(t_global *global, t_thread *thread)
Spawn philos and wait for them to complete.
Definition seat.c:54
void * breakfast(void *data)
Ponder, eat, sleep, repeat.
Definition breakfast.c:65
static void monitor_eat_quota(t_global *global, t_thread *thread, int i)
End simulation once all philos are full.
Definition seat.c:34
int setup(t_global *global, t_thread **thread)
Allocate fork array and thread structure, initialize mutexes.
Definition setup.c:84
int seat(t_opt opt)
Allocate for, initialize, seat, wait on (pun intended), and free all philos.
Definition seat.c:90
Definition philo.h:26