philosophers_prep/rendu/thread_basics.c

73 lines
1.9 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* thread_basics.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ruiferna <ruiferna@student.42porto.com> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/10/07 15:05:44 by ruiferna #+# #+# */
/* Updated: 2025/10/07 16:46:44 by ruiferna ### ########.fr */
/* */
/* ************************************************************************** */
// https://www.youtube.com/watch?v=ldJ8WGZVXZk
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
typedef struct s_thread_data
{
int id;
int p_times;
} t_thread_data;
void *print_hello(void *arg);
int main(int ac, char **av)
{
pthread_t thread1;
pthread_t thread2;
t_thread_data *data1;
t_thread_data *data2;
if (ac != 2)
{
printf("Usage: %s <number_of_times>\n", av[0]);
return (1);
}
int p_times = atoi(av[1]);
data1 = malloc(sizeof(t_thread_data));
data1->id = 1;
data1->p_times = p_times;
data2 = malloc(sizeof(t_thread_data));
data2->id = 2;
data2->p_times = p_times;
pthread_create(&thread1, NULL, print_hello, data1);
pthread_create(&thread2, NULL, print_hello, data2);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
free(data1);
free(data2);
return (0);
}
void *print_hello(void *arg)
{
int i = 0;
t_thread_data *data = (t_thread_data *)arg;
while (i < data->p_times)
{
printf("Thread %i: Hello from thread %i\n", data->id, data->id);
i++;
}
return (NULL);
}