Translated subjects to English
This commit is contained in:
parent
0a91d2dabd
commit
24da1f174c
@ -5,18 +5,18 @@ pthread_detach, pthread_join, pthread_mutex_init, pthread_mutex_destroy,
|
|||||||
pthread_mutex_lock, pthread_mutex_unlock, usleep, gettimeofday
|
pthread_mutex_lock, pthread_mutex_unlock, usleep, gettimeofday
|
||||||
------------------------------------------------------------------------
|
------------------------------------------------------------------------
|
||||||
|
|
||||||
Implementa o problema completo dos filósofos com parsing de argumentos:
|
Implement the complete philosophers problem with argument parsing:
|
||||||
|
|
||||||
Argumentos: `number_of_philosophers time_to_die time_to_eat time_to_sleep [number_of_times_must_eat]`
|
Arguments: `number_of_philosophers time_to_die time_to_eat time_to_sleep [number_of_times_must_eat]`
|
||||||
|
|
||||||
Comportamento:
|
Behavior:
|
||||||
- Cada filósofo alterna: pensar → tentar pegar forks → comer → largar forks → dormir
|
- Each philosopher alternates: thinking → trying to grab forks → eating → dropping forks → sleeping
|
||||||
- Se um filósofo não comer dentro de `time_to_die`, morre e programa termina
|
- If a philosopher doesn't eat within `time_to_die`, they die and the program terminates
|
||||||
- Se `number_of_times_must_eat` especificado, programa termina quando todos comeram esse número de vezes
|
- If `number_of_times_must_eat` is specified, the program terminates when all have eaten that many times
|
||||||
- Thread monitor verifica mortes a cada 1ms
|
- Monitor thread checks for deaths every 1ms
|
||||||
|
|
||||||
Uso: `./philosophers_args 5 800 200 200` ou `./philosophers_args 5 800 200 200 7`
|
Usage: `./philosophers_args 5 800 200 200` or `./philosophers_args 5 800 200 200 7`
|
||||||
|
|
||||||
Hint: Este é praticamente o projeto Philosophers completo.
|
Hint: This is practically the complete Philosophers project.
|
||||||
Implementa parsing robusto de argumentos, validação de inputs, e cleanup adequado de recursos.
|
Implement robust argument parsing, input validation, and proper resource cleanup.
|
||||||
A thread monitor é crítica - deve detectar morte rapidamente sem afetar performance.
|
The monitor thread is critical - it must detect death quickly without affecting performance.
|
||||||
@ -5,20 +5,20 @@ pthread_join, pthread_mutex_init, pthread_mutex_destroy,
|
|||||||
pthread_mutex_lock, pthread_mutex_unlock, usleep, gettimeofday
|
pthread_mutex_lock, pthread_mutex_unlock, usleep, gettimeofday
|
||||||
----------------------------------------------------------------------------------------
|
----------------------------------------------------------------------------------------
|
||||||
|
|
||||||
Cria uma versão do problema dos filósofos que:
|
Create a version of the philosophers problem that:
|
||||||
1. Detecta e reporta possíveis data races
|
1. Detects and reports possible data races
|
||||||
2. Testa diferentes estratégias de otimização:
|
2. Tests different optimization strategies:
|
||||||
- Estratégia A: mutex global para todas as operações
|
- Strategy A: global mutex for all operations
|
||||||
- Estratégia B: mutex por fork + mutex para impressão
|
- Strategy B: mutex per fork + mutex for printing
|
||||||
- Estratégia C: minimizar lock time
|
- Strategy C: minimize lock time
|
||||||
|
|
||||||
Inclui stress test: roda 100 iterações com diferentes configurações e reporta:
|
Include stress test: run 100 iterations with different configurations and report:
|
||||||
- Número de data races detectadas
|
- Number of data races detected
|
||||||
- Performance (tempo total)
|
- Performance (total time)
|
||||||
- Número de mortes
|
- Number of deaths
|
||||||
|
|
||||||
Uso: `./race_detector 4 410 200 200`
|
Usage: `./race_detector 4 410 200 200`
|
||||||
|
|
||||||
Hint: Use ferramentas como `valgrind --tool=helgrind` para detectar data races.
|
Hint: Use tools like `valgrind --tool=helgrind` to detect data races.
|
||||||
No projeto real, qualquer data race resulta em nota 0.
|
In the real project, any data race results in a grade of 0.
|
||||||
Testa com números ímpares e pares de filósofos, e com time_to_die muito próximo de time_to_eat.
|
Test with odd and even numbers of philosophers, and with time_to_die very close to time_to_eat.
|
||||||
@ -5,20 +5,20 @@ pthread_create, pthread_detach, pthread_join, usleep, gettimeofday,
|
|||||||
waitpid, sem_open, sem_close, sem_post, sem_wait, sem_unlink
|
waitpid, sem_open, sem_close, sem_post, sem_wait, sem_unlink
|
||||||
-------------------------------------------------------------------------
|
-------------------------------------------------------------------------
|
||||||
|
|
||||||
Implementa a versão bonus do Philosophers:
|
Implement the bonus version of Philosophers:
|
||||||
- Cada filósofo é um processo separado (não thread)
|
- Each philosopher is a separate process (not thread)
|
||||||
- Usa semáforos POSIX nomeados para coordenação
|
- Use named POSIX semaphores for coordination
|
||||||
- Processo pai monitora todos os processos filhos
|
- Parent process monitors all child processes
|
||||||
- Se um filósofo morre, mata todos os outros processos
|
- If a philosopher dies, kill all other processes
|
||||||
|
|
||||||
Funcionalidades adicionais:
|
Additional features:
|
||||||
- Cleanup adequado de semáforos nomeados
|
- Proper cleanup of named semaphores
|
||||||
- Handling de sinais (SIGINT, SIGTERM)
|
- Signal handling (SIGINT, SIGTERM)
|
||||||
- Relatório final com estatísticas
|
- Final report with statistics
|
||||||
|
|
||||||
Uso: `./philosophers_bonus 5 800 200 200 7`
|
Usage: `./philosophers_bonus 5 800 200 200 7`
|
||||||
|
|
||||||
Hint: Bonus part usa processos em vez de threads.
|
Hint: Bonus part uses processes instead of threads.
|
||||||
Semáforos POSIX nomeados permitem comunicação entre processos.
|
Named POSIX semaphores allow communication between processes.
|
||||||
Usa fork() para criar processos filhos e waitpid() para monitorizar.
|
Use fork() to create child processes and waitpid() to monitor.
|
||||||
O cleanup de semáforos é crucial - usa sem_unlink() e handling de sinais para cleanup em caso de interrupção.
|
Semaphore cleanup is crucial - use sem_unlink() and signal handling for cleanup in case of interruption.
|
||||||
@ -4,16 +4,16 @@ Allowed functions: memset, printf, malloc, free, write, pthread_create,
|
|||||||
pthread_detach, pthread_join, usleep, gettimeofday
|
pthread_detach, pthread_join, usleep, gettimeofday
|
||||||
-------------------------------------------------------------------------------
|
-------------------------------------------------------------------------------
|
||||||
|
|
||||||
Cria um programa que lance 2 threads. Cada thread deve imprimir o seu ID e uma mensagem diferente.
|
Create a program that launches 2 threads. Each thread should print its ID and a different message.
|
||||||
O programa principal deve esperar que ambas as threads terminem antes de sair.
|
The main program must wait for both threads to finish before exiting.
|
||||||
|
|
||||||
Thread 1 deve imprimir: "Thread 1: Hello from thread 1"
|
Thread 1 should print: "Thread 1: Hello from thread 1"
|
||||||
Thread 2 deve imprimir: "Thread 2: Hello from thread 2"
|
Thread 2 should print: "Thread 2: Hello from thread 2"
|
||||||
|
|
||||||
O programa deve aceitar como argumento o número de mensagens que cada thread deve imprimir.
|
The program must accept as an argument the number of messages each thread should print.
|
||||||
|
|
||||||
Uso: `./thread_basics 5`
|
Usage: `./thread_basics 5`
|
||||||
|
|
||||||
Hint: Este exercício ensina-te a base de pthread_create e pthread_join.
|
Hint: This exercise teaches you the basics of pthread_create and pthread_join.
|
||||||
Lembra-te de verificar os valores de retorno das funções pthread.
|
Remember to check the return values of pthread functions.
|
||||||
Usa uma estrutura para passar argumentos às threads.
|
Use a structure to pass arguments to threads.
|
||||||
|
|||||||
@ -5,14 +5,14 @@ pthread_join, pthread_mutex_init, pthread_mutex_destroy
|
|||||||
pthread_mutex_lock, pthread_mutex_unlock, usleep, gettimeofday
|
pthread_mutex_lock, pthread_mutex_unlock, usleep, gettimeofday
|
||||||
--------------------------------------------------------------------------------------
|
--------------------------------------------------------------------------------------
|
||||||
|
|
||||||
Cria um programa com uma variável global `counter` inicializada a 0.
|
Create a program with a global variable `counter` initialized to 0.
|
||||||
Lança 4 threads que incrementam esta variável 1000 vezes cada uma.
|
Launch 4 threads that increment this variable 1000 times each.
|
||||||
Usa um mutex para proteger o acesso à variável.
|
Use a mutex to protect access to the variable.
|
||||||
|
|
||||||
O programa deve imprimir o valor final de `counter` (deve ser 4000) e o tempo total de execução.
|
The program should print the final value of `counter` (should be 4000) and the total execution time.
|
||||||
|
|
||||||
Uso: `./mutex_basics`
|
Usage: `./mutex_basics`
|
||||||
|
|
||||||
Hint: Sem mutex, vais ver valores incorretos devido a race conditions.
|
Hint: Without a mutex, you will see incorrect values due to race conditions.
|
||||||
O mutex garante que apenas uma thread acede à variável de cada vez.
|
The mutex ensures that only one thread accesses the variable at a time.
|
||||||
Este é o conceito fundamental para o projeto Philosophers.
|
This is the fundamental concept for the Philosophers project.
|
||||||
@ -5,19 +5,19 @@ pthread_join, pthread_mutex_init, pthread_mutex_destroy,
|
|||||||
pthread_mutex_lock, pthread_mutex_unlock, usleep, gettimeofday
|
pthread_mutex_lock, pthread_mutex_unlock, usleep, gettimeofday
|
||||||
---------------------------------------------------------------------------------------
|
---------------------------------------------------------------------------------------
|
||||||
|
|
||||||
Implementa as seguintes funções:
|
Implement the following functions:
|
||||||
- `long long get_current_time()` - retorna o tempo atual em milissegundos
|
- `long long get_current_time()` - returns the current time in milliseconds
|
||||||
- `void precise_sleep(int ms)` - dorme por exatamente X milissegundos
|
- `void precise_sleep(int ms)` - sleeps for exactly X milliseconds
|
||||||
- `long long time_diff(long long start, long long end)` - calcula diferença entre tempos
|
- `long long time_diff(long long start, long long end)` - calculates difference between times
|
||||||
|
|
||||||
Cria um programa que testa estas funções:
|
Create a program that tests these functions:
|
||||||
1. Mede o tempo de início
|
1. Measure start time
|
||||||
2. Dorme por 100ms usando precise_sleep
|
2. Sleep for 100ms using precise_sleep
|
||||||
3. Mede o tempo de fim
|
3. Measure end time
|
||||||
4. Imprime a diferença (deve ser ~100ms)
|
4. Print the difference (should be ~100ms)
|
||||||
|
|
||||||
Uso: `./precise_timing`
|
Usage: `./precise_timing`
|
||||||
|
|
||||||
Hint: gettimeofday() é crucial no projeto Philosophers.
|
Hint: gettimeofday() is crucial in the Philosophers project.
|
||||||
usleep() não é sempre preciso, por isso tens de verificar o tempo periodicamente.
|
usleep() is not always precise, so you need to check the time periodically.
|
||||||
No Philosophers, o timing preciso é essencial para detectar mortes.
|
In Philosophers, precise timing is essential for detecting deaths.
|
||||||
|
|||||||
@ -1,23 +1,23 @@
|
|||||||
**Assignment name**: state_monitor
|
Assignment name: state_monitor
|
||||||
**Expected files**: state_monitor.c
|
Expected files: state_monitor.c
|
||||||
**Allowed functions**: memset, printf, malloc, free, write, pthread_create,
|
Allowed functions: memset, printf, malloc, free, write, pthread_create,
|
||||||
pthread_detach, pthread_join, pthread_mutex_init, pthread_mutex_destroy,
|
pthread_detach, pthread_join, pthread_mutex_init, pthread_mutex_destroy,
|
||||||
pthread_mutex_lock, pthread_mutex_unlock, usleep, gettimeofday
|
pthread_mutex_lock, pthread_mutex_unlock, usleep, gettimeofday
|
||||||
---------------------------------------------------------------------------
|
---------------------------------------------------------------------------
|
||||||
|
|
||||||
Cria um programa com 3 threads "worker" e 1 thread "monitor":
|
Create a program with 3 "worker" threads and 1 "monitor" thread:
|
||||||
|
|
||||||
**Worker threads**: Cada thread alterna entre 3 estados:
|
Worker threads: Each thread alternates between 3 states:
|
||||||
- WORKING (2 segundos)
|
- WORKING (2 seconds)
|
||||||
- RESTING (1 segundo)
|
- RESTING (1 second)
|
||||||
- THINKING (1.5 segundos)
|
- THINKING (1.5 seconds)
|
||||||
|
|
||||||
Cada mudança de estado deve ser impressa com timestamp: `[timestamp] Worker X is WORKING`
|
Each state change should be printed with timestamp: `[timestamp] Worker X is WORKING`
|
||||||
|
|
||||||
**Monitor thread**: Verifica se algum worker está no mesmo estado há mais de 3 segundos.
|
Monitor thread: Checks if any worker has been in the same state for more than 3 seconds.
|
||||||
Se sim, imprime: `[timestamp] WARNING: Worker X stuck in STATE`
|
If so, prints: `[timestamp] WARNING: Worker X stuck in STATE`
|
||||||
|
|
||||||
**Uso**: `./state_monitor`
|
Usage: `./state_monitor`
|
||||||
|
|
||||||
**Hint**: Use enums para os estados. O monitor thread simula a verificação de morte no Philosophers,
|
Hint: Use enums for the states. The monitor thread simulates death checking in Philosophers,
|
||||||
tens de verificar continuamente sem interferir com os workers. Usa mutex para proteger o acesso aos estados.
|
you need to check continuously without interfering with workers. Use mutex to protect access to states.
|
||||||
|
|||||||
@ -5,19 +5,19 @@ pthread_detach, pthread_join, pthread_mutex_init, pthread_mutex_destroy,
|
|||||||
pthread_mutex_lock, pthread_mutex_unlock, usleep, gettimeofday
|
pthread_mutex_lock, pthread_mutex_unlock, usleep, gettimeofday
|
||||||
---------------------------------------------------------------------------
|
---------------------------------------------------------------------------
|
||||||
|
|
||||||
Implementa o problema clássico Producer-Consumer:
|
Implement the classic Producer-Consumer problem:
|
||||||
- 2 threads Producer: produzem items (números de 1 a 100) e colocam num buffer
|
- 2 Producer threads: produce items (numbers from 1 to 100) and place them in a buffer
|
||||||
- 2 threads Consumer: consomem items do buffer e processam-nos
|
- 2 Consumer threads: consume items from the buffer and process them
|
||||||
- Buffer partilhado com capacidade limitada (10 items)
|
- Shared buffer with limited capacity (10 items)
|
||||||
|
|
||||||
Regras:
|
Rules:
|
||||||
- Producers devem esperar se buffer estiver cheio
|
- Producers must wait if buffer is full
|
||||||
- Consumers devem esperar se buffer estiver vazio
|
- Consumers must wait if buffer is empty
|
||||||
- Não deve haver race conditions
|
- There should be no race conditions
|
||||||
- Imprime quando items são produzidos/consumidos
|
- Print when items are produced/consumed
|
||||||
|
|
||||||
Uso: `./producer_consumer`
|
Usage: `./producer_consumer`
|
||||||
|
|
||||||
Hint: Este exercício ensina-te a coordenação entre múltiplas threads com recursos limitados.
|
Hint: This exercise teaches you coordination between multiple threads with limited resources.
|
||||||
É similar ao problema dos forks no Philosophers.
|
It's similar to the forks problem in Philosophers.
|
||||||
Usa mutexes para proteger o buffer e condition variables ou sleep para coordenação.
|
Use mutexes to protect the buffer and condition variables or sleep for coordination.
|
||||||
@ -3,22 +3,21 @@ Expected files: deadlock_demo.c
|
|||||||
Allowed functions: memset, printf, malloc, free, write, pthread_create, pthread_detach,
|
Allowed functions: memset, printf, malloc, free, write, pthread_create, pthread_detach,
|
||||||
pthread_join, pthread_mutex_init, pthread_mutex_destroy, pthread_mutex_lock,
|
pthread_join, pthread_mutex_init, pthread_mutex_destroy, pthread_mutex_lock,
|
||||||
pthread_mutex_unlock, usleep, gettimeofday
|
pthread_mutex_unlock, usleep, gettimeofday
|
||||||
|
---------------------------------------------------------------------------------------
|
||||||
|
|
||||||
---
|
Create a program that demonstrates deadlock and then shows how to solve it:
|
||||||
|
|
||||||
Cria um programa que demonstra deadlock e depois mostra como o resolver:
|
Part 1 - Deadlock:
|
||||||
|
|
||||||
Parte 1 - Deadlock:
|
|
||||||
2 threads, 2 mutexes (mutex_a, mutex_b)
|
2 threads, 2 mutexes (mutex_a, mutex_b)
|
||||||
- Thread 1: lock mutex_a → sleep 100ms → lock mutex_b → unlock ambos
|
- Thread 1: lock mutex_a → sleep 100ms → lock mutex_b → unlock both
|
||||||
- Thread 2: lock mutex_b → sleep 100ms → lock mutex_a → unlock ambos
|
- Thread 2: lock mutex_b → sleep 100ms → lock mutex_a → unlock both
|
||||||
|
|
||||||
Parte 2 - Solução: Ambas threads fazem lock dos mutexes na mesma ordem.
|
Part 2 - Solution: Both threads lock the mutexes in the same order.
|
||||||
|
|
||||||
O programa deve aceitar um argumento: 0 para deadlock, 1 para solução.
|
The program must accept an argument: 0 for deadlock, 1 for solution.
|
||||||
|
|
||||||
Uso: `./deadlock_demo 0` (demonstra deadlock)
|
Usage: `./deadlock_demo 0` (demonstrates deadlock)
|
||||||
Uso: `./deadlock_demo 1` (demonstra solução)
|
Usage: `./deadlock_demo 1` (demonstrates solution)
|
||||||
|
|
||||||
Hint: Deadlock é um risco real no Philosophers quando filósofos tentam pegar forks em ordens diferentes.
|
Hint: Deadlock is a real risk in Philosophers when philosophers try to grab forks in different orders.
|
||||||
A solução mais comum é ordenar os recursos (forks com IDs mais baixos primeiro).
|
The most common solution is to order the resources (forks with lower IDs first).
|
||||||
|
|||||||
@ -1,23 +1,23 @@
|
|||||||
**Assignment name**: limited_resources
|
Assignment name: limited_resources
|
||||||
**Expected files**: limited_resources.c
|
Expected files: limited_resources.c
|
||||||
**Allowed functions**: memset, printf, malloc, free, write, pthread_create, pthread_detach,
|
Allowed functions: memset, printf, malloc, free, write, pthread_create, pthread_detach,
|
||||||
pthread_join, pthread_mutex_init, pthread_mutex_destroy, pthread_mutex_lock, pthread_mutex_unlock, usleep, gettimeofday
|
pthread_join, pthread_mutex_init, pthread_mutex_destroy, pthread_mutex_lock,
|
||||||
|
pthread_mutex_unlock, usleep, gettimeofday
|
||||||
|
---------------------------------------------------------------------------------------
|
||||||
|
|
||||||
---
|
Simulate a library with 3 computers shared among 10 students:
|
||||||
|
- Each student (thread) wants to use a computer for 2-5 seconds (random time)
|
||||||
|
- Only 3 students can use computers simultaneously
|
||||||
|
- Implement a "semaphore" using mutexes and a counter variable
|
||||||
|
|
||||||
Simula uma biblioteca com 3 computadores partilhados entre 10 estudantes:
|
Print when students:
|
||||||
- Cada estudante (thread) quer usar um computador por 2-5 segundos (tempo aleatório)
|
- Arrive at the library
|
||||||
- Apenas 3 estudantes podem usar computadores simultaneamente
|
- Get a computer
|
||||||
- Implementa um "semáforo" usando mutexes e uma variável contador
|
- Finish using the computer
|
||||||
|
- Leave the library
|
||||||
|
|
||||||
Imprime quando estudantes:
|
Usage: `./limited_resources`
|
||||||
- Chegam à biblioteca
|
|
||||||
- Conseguem um computador
|
|
||||||
- Terminam de usar o computador
|
|
||||||
- Saem da biblioteca
|
|
||||||
|
|
||||||
**Uso**: `./limited_resources`
|
Hint: Since POSIX semaphores are not allowed in the mandatory part,
|
||||||
|
implement your own semaphore with mutex + counter + condition logic.
|
||||||
**Hint**: Como POSIX semáforos não são permitidos no mandatory part,
|
This exercise simulates resource limitation like in Philosophers with forks.
|
||||||
implementa o teu próprio semáforo com mutex + contador + condition logic.
|
|
||||||
Este exercício simula a limitação de recursos como no Philosophers com forks.
|
|
||||||
@ -4,16 +4,16 @@ Allowed functions: memset, printf, malloc, free, write, pthread_create, pthread_
|
|||||||
pthread_join, pthread_mutex_init, pthread_mutex_destroy, pthread_mutex_lock, pthread_mutex_unlock, usleep, gettimeofday
|
pthread_join, pthread_mutex_init, pthread_mutex_destroy, pthread_mutex_lock, pthread_mutex_unlock, usleep, gettimeofday
|
||||||
---
|
---
|
||||||
|
|
||||||
Implementa uma versão simplificada do problema dos filósofos:
|
Implement a simplified version of the dining philosophers problem:
|
||||||
- 3 filósofos sentados numa mesa circular
|
- 3 philosophers seated at a circular table
|
||||||
- 3 forks (um entre cada par de filósofos)
|
- 3 forks (one between each pair of philosophers)
|
||||||
- Cada filósofo alterna entre: pensar (1s) → pegar forks → comer (1s) → largar forks → repetir
|
- Each philosopher alternates between: thinking (1s) → grabbing forks → eating (1s) → dropping forks → repeat
|
||||||
- Programa corre por 10 segundos e depois pára
|
- Program runs for 10 seconds and then stops
|
||||||
|
|
||||||
Cada ação deve ser impressa: `[timestamp] Philosopher X is thinking/eating`
|
Each action should be printed: `[timestamp] Philosopher X is thinking/eating`
|
||||||
|
|
||||||
Uso: `./simple_philosophers`
|
Usage: `./simple_philosophers`
|
||||||
|
|
||||||
Hint: Este é o núcleo do projeto Philosophers. Cada fork é protegido por um mutex.
|
Hint: This is the core of the Philosophers project. Each fork is protected by a mutex.
|
||||||
Para evitar deadlock, implementa uma ordem consistente para pegar forks (fork com ID menor primeiro).
|
To avoid deadlock, implement a consistent order for grabbing forks (fork with lower ID first).
|
||||||
Usa uma thread monitor para parar após 10s.
|
Use a monitor thread to stop after 10s.
|
||||||
@ -3,19 +3,19 @@ Expected files: death_monitor.c
|
|||||||
Allowed functions: memset, printf, malloc, free, write, pthread_create, pthread_detach,
|
Allowed functions: memset, printf, malloc, free, write, pthread_create, pthread_detach,
|
||||||
pthread_join, pthread_mutex_init, pthread_mutex_destroy, pthread_mutex_lock,
|
pthread_join, pthread_mutex_init, pthread_mutex_destroy, pthread_mutex_lock,
|
||||||
pthread_mutex_unlock, usleep, gettimeofday
|
pthread_mutex_unlock, usleep, gettimeofday
|
||||||
---
|
---------------------------------------------------------------------------------------
|
||||||
|
|
||||||
Cria um sistema com:
|
Create a system with:
|
||||||
- 4 threads "worker" que fazem trabalho por períodos variados (1-4 segundos)
|
- 4 "worker" threads that do work for varied periods (1-4 seconds)
|
||||||
- 1 thread monitor que verifica se algum worker não dá "sinal de vida" há mais de 3 segundos
|
- 1 monitor thread that checks if any worker hasn't given a "sign of life" for more than 3 seconds
|
||||||
- Workers devem atualizar `last_activity_time` a cada iteração
|
- Workers must update `last_activity_time` at each iteration
|
||||||
- Monitor verifica a cada 100ms e imprime aviso se detectar worker "morto"
|
- Monitor checks every 100ms and prints warning if it detects a "dead" worker
|
||||||
|
|
||||||
Simula "morte" fazendo um worker parar aleatoriamente.
|
Simulate "death" by making a worker stop randomly.
|
||||||
|
|
||||||
Uso: `./death_monitor`
|
Usage: `./death_monitor`
|
||||||
|
|
||||||
Hint: Este exercício simula a detecção de morte no Philosophers.
|
Hint: This exercise simulates death detection in Philosophers.
|
||||||
O monitor thread deve verificar continuamente sem bloquear os workers.
|
The monitor thread must check continuously without blocking the workers.
|
||||||
Usa mutex para proteger `last_activity_time`.
|
Use mutex to protect `last_activity_time`.
|
||||||
A detecção deve ser rápida (dentro de 10ms no projeto real).
|
Detection must be fast (within 10ms in the real project).
|
||||||
74
README.md
74
README.md
@ -1,62 +1,62 @@
|
|||||||
# Exercícios Preparatórios — Projeto Philosophers
|
# Preparatory Exercises — Philosophers Project
|
||||||
|
|
||||||
Bem-vindo ao repositório de exercícios práticos desenhados para construir, passo a passo, todos os conceitos necessários para dominar o projeto Philosophers da 42. Aqui vais encontrar desafios progressivos sobre threads, mutexes, deadlocks, sincronização, semáforos, timing, e muito mais em C.
|
Welcome to the repository of practical exercises designed to build, step by step, all the concepts necessary to master the 42 Philosophers project. Here you will find progressive challenges about threads, mutexes, deadlocks, synchronization, semaphores, timing, and much more in C.
|
||||||
|
|
||||||
## Objetivo
|
## Objective
|
||||||
|
|
||||||
A proposta deste repositório é guiar estudantes pela aprendizagem real de programação concorrente, partindo do absoluto básico até à implementação de sistemas completos e robustos capazes de resolver o clássico problema dos Filósofos, incluindo as regras e desafios da bonus part.
|
The purpose of this repository is to guide students through real concurrent programming learning, starting from the absolute basics up to the implementation of complete and robust systems capable of solving the classic Dining Philosophers problem, including the rules and challenges of the bonus part.
|
||||||
|
|
||||||
## Estrutura dos Exercícios
|
## Exercise Structure
|
||||||
|
|
||||||
Cada exercício segue uma estrutura clara e normalizada, incluindo:
|
Each exercise follows a clear and standardized structure, including:
|
||||||
|
|
||||||
- **Assignment name**
|
- **Assignment name**
|
||||||
- **Expected files**
|
- **Expected files**
|
||||||
- **Allowed functions**
|
- **Allowed functions**
|
||||||
- **Descrição do problema**
|
- **Problem description**
|
||||||
- **Sugestão/Hint para a resolução**
|
- **Hint/Suggestion for resolution**
|
||||||
|
|
||||||
### Lista de Exercícios
|
### Exercise List
|
||||||
|
|
||||||
| Nº | Nome | Conteúdo-chave |
|
| No | Name | Key Content |
|
||||||
|----|---------------------------|---------------------------------------------|
|
|----|---------------------------|---------------------------------------------|
|
||||||
| 1 | thread_basics | Threads, pthread_create, pthread_join |
|
| 1 | thread_basics | Threads, pthread_create, pthread_join |
|
||||||
| 2 | mutex_basics | Mutexes, race conditions |
|
| 2 | mutex_basics | Mutexes, race conditions |
|
||||||
| 3 | precise_timing | gettimeofday, usleep, timing |
|
| 3 | precise_timing | gettimeofday, usleep, timing |
|
||||||
| 4 | state_monitor | Monitorização, enums, padrões monitor |
|
| 4 | state_monitor | Monitoring, enums, monitor patterns |
|
||||||
| 5 | producer_consumer | Sincronização, coordination problems |
|
| 5 | producer_consumer | Synchronization, coordination problems |
|
||||||
| 6 | deadlock_demo | Deadlock, prevenção de deadlock |
|
| 6 | deadlock_demo | Deadlock, deadlock prevention |
|
||||||
| 7 | limited_resources | Semáforo manual, acesso limitado |
|
| 7 | limited_resources | Manual semaphore, limited access |
|
||||||
| 8 | simple_philosophers | Problema dos filósofos simplificado |
|
| 8 | simple_philosophers | Simplified philosophers problem |
|
||||||
| 9 | death_monitor | Monitorização de vida, threads watchdog |
|
| 9 | death_monitor | Life monitoring, watchdog threads |
|
||||||
| 10 | philosophers_args | Implementação 'full', argumentos |
|
| 10 | philosophers_args | Full implementation, arguments |
|
||||||
| 11 | race_detector | Data races, otimização de locks |
|
| 11 | race_detector | Data races, lock optimization |
|
||||||
| 12 | philosophers_bonus | Processos, semáforos POSIX, bonus part |
|
| 12 | philosophers_bonus | Processes, POSIX semaphores, bonus part |
|
||||||
|
|
||||||
## Como usar
|
## How to Use
|
||||||
|
|
||||||
1. **Cada exercício é independente.** Recomenda-se seguir pela ordem, para garantir a aprendizagem progressiva.
|
1. **Each exercise is independent.** It is recommended to follow them in order to ensure progressive learning.
|
||||||
2. **Compilar cada exercício:**
|
2. **Compile each exercise:**
|
||||||
```sh
|
```sh
|
||||||
gcc -Wall -Wextra -Werror -pthread <nome_ficheiro>.c -o <programa>
|
gcc -Wall -Wextra -Werror -pthread <filename>.c -o <program>
|
||||||
```
|
```
|
||||||
3. **Executar cada binário** seguindo as instruções e exemplos do cabeçalho do exercício.
|
3. **Run each binary** following the instructions and examples in the exercise header.
|
||||||
|
|
||||||
## Requisitos Técnicos
|
## Technical Requirements
|
||||||
|
|
||||||
- Compilador C (ex: gcc)
|
- C Compiler (e.g., gcc)
|
||||||
- Ambiente POSIX (Linux ou Mac OS X recomendado)
|
- POSIX environment (Linux or Mac OS X recommended)
|
||||||
- Bibliotecas pthreads standard
|
- Standard pthreads libraries
|
||||||
|
|
||||||
## Recomendações
|
## Recommendations
|
||||||
|
|
||||||
- Não uses funções externas às permitidas.
|
- Don't use external functions beyond those allowed.
|
||||||
- Lê atentamente os hints fornecidos para cada exercício.
|
- Carefully read the hints provided for each exercise.
|
||||||
- Analisa erros de race condition e deadlocks usando ferramentas como `valgrind --tool=helgrind`.
|
- Analyze race condition and deadlock errors using tools like `valgrind --tool=helgrind`.
|
||||||
- Consulta [The Little Book of Semaphores](https://greenteapress.com/wp/semaphores/) para cimentar conceitos.
|
- Consult [The Little Book of Semaphores](https://greenteapress.com/wp/semaphores/) to solidify concepts.
|
||||||
|
|
||||||
## Créditos e Referências
|
## Credits and References
|
||||||
|
|
||||||
- Inspirado no livro open-source **The Little Book of Semaphores** por Allen B. Downey.
|
- Inspired by the open-source book **The Little Book of Semaphores** by Allen B. Downey.
|
||||||
- Estrutura e avaliação baseadas no formato dos projetos 42.
|
- Structure and evaluation based on the 42 project format.
|
||||||
- Problema clássico dos Filósofos por Edsger W. Dijkstra.
|
- Classic Dining Philosophers problem by Edsger W. Dijkstra.
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user