68 lines
2.0 KiB
C
68 lines
2.0 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* mutex_basics.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: ruiferna <ruiferna@student.42porto.com> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2025/10/07 16:09:59 by ruiferna #+# #+# */
|
|
/* Updated: 2025/10/07 20:25:56 by ruiferna ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include <stdio.h>
|
|
#include <pthread.h>
|
|
#include <stdlib.h>
|
|
#include <sys/time.h>
|
|
|
|
void *increase_amount(void *arg);
|
|
|
|
pthread_mutex_t mutex;
|
|
|
|
int main()
|
|
{
|
|
pthread_t thread1;
|
|
pthread_t thread2;
|
|
pthread_t thread3;
|
|
pthread_t thread4;
|
|
|
|
int value = 0;
|
|
struct timeval start, end;
|
|
long long elapsed_ms;
|
|
|
|
pthread_mutex_init(&mutex, NULL);
|
|
|
|
gettimeofday(&start, NULL);
|
|
|
|
pthread_create(&thread1, NULL, increase_amount, &value);
|
|
pthread_create(&thread2, NULL, increase_amount, &value);
|
|
pthread_create(&thread3, NULL, increase_amount, &value);
|
|
pthread_create(&thread4, NULL, increase_amount, &value);
|
|
|
|
pthread_join(thread1, NULL);
|
|
pthread_join(thread2, NULL);
|
|
pthread_join(thread3, NULL);
|
|
pthread_join(thread4, NULL);
|
|
|
|
gettimeofday(&end, NULL);
|
|
elapsed_ms = (long long)(end.tv_sec - start.tv_sec) * 1000LL + (end.tv_usec - start.tv_usec) / 1000LL;
|
|
|
|
pthread_mutex_destroy(&mutex);
|
|
printf("counter: %d\n", value);
|
|
printf("time: %lld ms\n", elapsed_ms);
|
|
return (0);
|
|
}
|
|
|
|
void *increase_amount(void *arg)
|
|
{
|
|
pthread_mutex_lock(&mutex);
|
|
int *amount = (int *)arg;
|
|
int i = 0;
|
|
while (i < 1000)
|
|
{
|
|
*amount +=1;
|
|
i++;
|
|
}
|
|
pthread_mutex_unlock(&mutex);
|
|
return (NULL);
|
|
} |