24
Silberschatz, Galvin and Gagne ©2009 perating System Concepts – 8 th Edition Chapter 4: Threads

Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

Embed Size (px)

Citation preview

Page 1: Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8th Edition

Chapter 4: Threads

Page 2: Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

4.2 Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8th Edition

Motivação

Threads são processos leves

Diferentes tarefas da aplicação podem ser implementadas como threads separados

Aplicável apenas às tarefas que possam ser paralelizadas

– Exemplos:

» Atualizar o display

» Buscar dados

» Verificar correção ortográfica

Page 3: Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

4.3 Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8th Edition

Motivação

A criação de processos é muito custosa

Criação de threads é mais simples

Vantagens do uso de threads

Simplificação do código

Aumento da eficiência

Page 4: Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

4.4 Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8th Edition

Processos mono e multithreads

Page 5: Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

4.5 Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8th Edition

Benefícios

Melhora o tempo de resposta• Programa continua executando mesmo

que algum thread seja bloqueado (thread no espaço de kernel)

Compartilhamento por padrão dos recursos do processo

• Não precisa de técnicas para criar uma memória compartilhada

É mais simples criar um thread do que um processo

• Não precisa alocar novos recursos e é fácil trocar contexto entre threads

Aumenta o paralelismo• Em máquinas com multiprocessamento

Page 6: Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

4.6 Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8th Edition

Programação com múltiplos cores

Sistemas com múltiplos cores impulsionam novas formas de programar

Maior eficiência na execução de programas

Contudo, existem algumas dificuldades

É possível paralelizar?

As tarefas paralelizáveis tem a mesma importância?

Quais conjuntos de dados pertencem a cada thread?

Se duas threads usam dados dependentes, como sincronizar o

acesso?

Como depurar o processo, se existem múltiplos caminhos de execução?

Page 7: Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

4.7 Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8th Edition

Arquitetura de Servidor Multithreaded

Page 8: Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

4.8 Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8th Edition

Execução concorrente em um sistema com único core

Page 9: Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

4.9 Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8th Edition

Execução paralela em um sistema multicore

Page 10: Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

4.10 Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8th Edition

Threads de usuários

Gerenciamento de threads feito por bibliotecas em nível de usuário

•Não depende de chamadas ao sistema para criar o thread ou para

mudar o contexto entre threads

•O bloqueio de um thread leva ao bloqueio de todo o processo

•A troca de contextos entre threads é feita mediante cooperação

Page 11: Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

4.11 Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8th Edition

Threads de kernel

Gerenciamento de threads feito pelo kernel

•Depende de chamadas ao sistema para criar o thread ou para mudar o

contexto

•O bloqueio de um thread não leva ao bloqueio de todo o processo

•A troca de contextos entre threads é feita mediante cooperação e

preempção

Page 12: Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

4.12 Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8th Edition

Modelos multithreads

Muitos para um

Um para um

Muitos para muitos

Page 13: Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

4.13 Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8th Edition

Muitos para um

Diversos threads de usuário mapeados em um único thread de kernel

Page 14: Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

4.14 Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8th Edition

Um para um

Cada thread de usuário mapeado em um thread de kernel

Page 15: Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

4.15 Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8th Edition

Modelo muitos para muitos

Permite que muitos threads de usuário sejam mapeados em muitos threads de kernel

Sistema operacional pode criar um número suficiente de threads de kernel

Page 16: Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

4.16 Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8th Edition

Bibliotecas de threads

Bibliotecas de thread dão ao programador uma interface para criar e gerenciar threads

Duas formas iniciais de implementação

Biblioteca inteiramente em espaço de usuário

Biblioteca em nível de kernel suportada pelo sistema operacional

Page 17: Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

4.17 Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8th Edition

Pthreads

Biblioteca de threads que pode ser provida tanto em nível de kernel como em nível de usuário

Interface especificada pelo padrão POSIX (IEEE 1003.1c) para criação e sincronização de threads

Define apenas a interface. A implementação fica a cargo da biblioteca

Amplamente utilizada em sistemas operacionais UNIX (Solaris, Linux, Mac OS X)

Page 18: Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

4.18 Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8th Edition

Algumas questões de threads….

O fork() duplica apenas o thread que o chama ou todos os threads do processo?

Depende da implementação

Cancelamento de threads

Terminar um thread, chamado de thread alvo, antes que ele chegue ao fim

Ex: Vários threads de busca em paralelo. Quando um thread encontra o dado, os outros podem ser finalizados.

Page 19: Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

4.19 Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8th Edition

Algumas questões de threads….

Page 20: Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

4.20 Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8th Edition

Algumas questões de threads….

Tratamento de sinais

Sinais são usados no sistema UNIX para notificar um processo que um evento ocorreu

Sinais devem ser entregues a processos

Mas se existem vários threads, para qual enviar?

Opções

– Descobrir para qual thread o sinal é direcionado

– Enviar o sinal para todos os threads

– Enviar o sinal para um conjunto de threads

– Criar um thread específico para receber sinais e notificar aos outros threads

Page 21: Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

4.21 Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8th Edition

Algumas questões de threads….

Conjuntos de threads

Pré-criação de um conjunto de threads prontos para serem usados

Vantagens

Mais rápido usar um thread pronto do que criar um novo thread

Garante que a aplicação não tentará criar threads em demasia, exaurindo os recursos do sistema operacional

Page 22: Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

4.22 Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8th Edition

Threads

Exemplos

Ex_sem_thread.py

Ex_sem_thread_processo.py

Ex_thread.py

Ex_threadv2.py

Ex_thread_mais_legal.py

Ex_thread_mais_legal_completo.py

Ex_legal_final.py

Page 23: Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

4.23 Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8th Edition

Exercícios

Lista 2 já disponível!

Page 24: Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads

Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8th Edition

End of Chapter 4