Sunum yükleniyor. Lütfen bekleyiniz

Sunum yükleniyor. Lütfen bekleyiniz

BÖLÜM 5 THREADS.

Benzer bir sunumlar


... konulu sunumlar: "BÖLÜM 5 THREADS."— Sunum transkripti:

1 BÖLÜM 5 THREADS

2 İçerik Giriş Multithreading Windows Threads Linux Threads

3 Giriş Eğer bir proses birden çok thread e sahip ise belirli bir zamanda birden çok görevi yürütebilir. Her thread aynı prosese ait diğer threadler ile prosesin kod kısmını data kısmını ve diğer işletim sistemi kaynaklarını (açık dosyalar, signals) paylaşır. Bir proses tekil bir thread kontrolü ile işletilen bir programdır.(heavyweight proses ) Thread = light weight process thread ID bir program counter bir register seti ve yığın içerir.

4 Single & MultiThreaded Process

5 Faydaları Cevap verebilirlik: Örneğin bir web browserda bir imaj yüklenirken başka bir tred kullanıcının başka işlemleri aynı anda yapmasına izin verir. Kaynak Paylaşımı: Varsayılan olarak, tredler ait oldukları prosesin kaynaklarının ve belleğini paylaşır. Ekonomi: Proses yaratmak tred yaratmaya göre daha maliyetli bir iştir. Proses yaratmak, tred yaratmaktan daha uzun sürer. Tred yaratmak ve aralarında geçiş yapmak daha az maliyetlidir. Çok işlemci Yapılarının Verimliliği: Bir çok işlemci mimarisinde, multitred yapıların faydaları kat kat artırılabilir.

6 Kullanıcı Tredleri Tred yönetimi, kullanıcı seviyesinde bir tred kütüphanesi tarafından gerçekleştirilir. Çekirdek, kullanıcı tredlerinin farkında değildir. Yaratılması ve yönetilmesi hızlıdır. 3 Temel tred kütüphanesi POSIX Pthreads Win32 threads Java threads

7 Çekirdek Tredleri İşletim sistemi tarafından desteklenirler.
Tredler üzerindeki tüm işlemler kernel’da gerçekleşir. Örnek: Windows Solaris Linux UNIX Mac OS X

8 Kullanıcı ve Çekirdek Tredleri

9 Thread States interrupt quantum expired init terminated admitted
5 durumda bulunabilirler: init: The thread is being created ready: The thread is waiting to be assigned to a CPU running: The thread’s instructions are being executed waiting: The thread is waiting for some event to occur terminated: The thread has finished execution interrupt quantum expired init terminated Newly created threads start there live in “init” state. After appropriate data structures are initialized (thread control block - TCB), the thread’s state is changed to “ready”. From “ready” state, a thread may get selected for execution and its state is changed by the scheduler to “running”. For a given system, there is exactly one thread in “running” state per processing unit (note that a CPU might have multiple processing units - multicore/hyperthreading). When the “running” thread issues an I/O request, it might block and change its state into “waiting”. Alternatively, a “running” thread’s time slice (quantum) may expire, in which case the thread’s state is changed back to “ready”. A “waiting” thread can move into “ready” state once the reason for its blocking disappears (I.e.; the I/O operation completes). Finally, a “running” thread might execute its last instruction - in which case its state changes to “terminated”. Operating systems often use heuristics to determine which one of the threads in “ready” state to select for execution. The Windows OS uses a priority-based scheme and maintains 32 ready queues of different priorities. admitted scheduler dispatch exit ready running waiting I/O or event completion waiting for I/O or event

10 Proses Verisi Her proses, gibi veriler içerir.
Sanal adres alanı (program kodu, global değişkenler, tred yığınları içerir) Prosesler birbirlerinin adres alanına yanlışlıkla da olsa erişemezler. Working Set Access Token Kernel nesneleri için Handle Table gibi veriler içerir.

11 Tred Verisi Her tred, User-mod stack (trede aktarılmış parametreler, çağrılan frameler vs.) Kernel-mod stack (sistem çağrıları için) Tred Local Storage (TLS) verisinin yerleşimini gösteren işaretçi dizisi State (wait, ready, running vs.) ve öncelik Donanım içeriği (Program counter, stack pointer, register değerleri, güncel erişim modu(user ya da kernel mod))

12 Struct Proc 2050 enum procstate { UNUSED, EMBRYO, SLEEPING, RUNNABLE, RUNNING, ZOMBIE }; 2051 2052 // Per−process state 2053 struct proc { 2054 uint sz; // Size of process memory (bytes) 2055 pde_t* pgdir; // Page table 2056 char *kstack; // Bottom of kernel stack for this process 2057 enum procstate state; // Process state 2058 volatile int pid; // Process ID 2059 struct proc *parent; // Parent process 2060 struct trapframe *tf; // Trap frame for current syscall 2061 struct context *context; // swtch() here to run process 2062 void *chan; // If non−zero, sleeping on chan 2063 int killed; // If non−zero, have been killed 2064 struct file *ofile[NOFILE]; // Open files 2065 struct inode *cwd; // Current directory 2066 char name[16]; // Process name (debugging) 2067 }; 2068 2069 // Process memory is laid out contiguously, low addresses first: 2070 // text 2071 // original data and bss 2072 // fixed−size stack 2073 // expandable heap

13 Kernel tred/user tred Bir prosesin kernel state’inin en önemli kısımları: Page table’ı ve işaret ettiği fiziksel bellek Kernel stack’i ve run state’i Tred bir işletim gerçekleştirir, durdurulabilir ve sonlandırılabilir. Proses bir sistem çağrısı yaptığında: CPU, prosesi işletmekten prosesin kernel tredini işletmeye anahtarlar. Prosesin kernel tredi, sistem çağrısı uygulamasını (read file) işletir ve sonra prosese geri döner. Kernel tredin state’i (yerel parametreler), kernel tred stack’inde depolanır. Her prosesin kernel stack’i, user stack’ten ayrıdır. Bu şekilde bir proses iki tred işletimine sahiptir: user tred ve kernel tred.

14 Process-Related Performance Counters
Object: Counter Function Process:%PrivilegedTime Percentage of time that the threads in the process have run in kernel Process:%ProcessorTime Percentage of CPU time that threads have used during specified interval Process:%UserTime Percentage of time that the threads in the process have run in user m. Process: ElapsedTime Total lifetime of process in seconds Process: ID Process PID – process IDs Process: ThreadCount Number of threads in a process

15 Thread-Related Performance Counters
Object: Counter Function Process: Priority Base Base priority of process: starting priority for thread within process Thread:%PrivilegedTime Percentage of time that the thread was run in kernel mode Thread:%ProcessorTime Percentage of CPU time that the threads has used during specified interval Thread:%UserTime Percentage of time that the thread has run in user mode Thread: ElapsedTime Total lifetime of process in seconds Thread: ID Process PID – process IDs Thread: ID Thread Thread ID

16 Thread-Related Performance Counters (contd.)
Object: Counter Function Thread: Priority Base Base priority of thread: may differ from the thread‘s starting priority Thread: Priority Current The thread‘s current dynamic priority Thread: Start Address The thread‘s starting virtual address (the same for most threads) Thread: Thread State Value from 0 through 7 – current state of thread Thread: Thread Wait Reason Value from 0 through 19 – reason why the thread is in wait state

17 Multithreading Modelleri
Many-to-One One-to-One Many-to-Many

18 Many-to-One Bir çok kullanıcı tredini tek bir kernel tredine map eder.
Tred yönetimi kullanıcı alanında yapılır. Kullanıcı-seviyeli tred kütüphaneleri, kernel tredlerini desteklemeyen many-to-one modelini kullanan işletim sistemi üzerinde gerçekleştirilirler.

19 Many-to-One

20 One-to-One Her kullanıcı tredini bir kernel tredine map eder.
Many-to-one modeline göre daha fazla eş zamanlılık sağlar. Birden çok tredin çoklu işlemciler üzerinde çalışabilmesine olanak tanır. Bu modelde, bir kullanıcı tredi yaratmak, uygun kernel tredin yaratılması ile gerçekleşir.

21 One-to-One

22 Many-to-Many Birden çok kullanıcı tredini eşit sayıda ya da daha az sayıda kernel tredine çoklar. Uygulama geliştiriciye istediği kadar tred yaratma şansı verir. Eş zamanlılık doğru olarak uygulanmış olmaz. Çünkü kernel belirli bir zamanda yalnızca bir tredi düzenleyebilir. One-to-one model daha iyi bir eş zamanlılık sağlarken, kullanıcı bir uygulamada çok fazla sayıda tred yaratmamalıdır. Many-to-many modeli ise tüm bu kısıtlamalardan kurtulmuştur. Uygulama geliştiriciler istedikleri kadar kullanıcı prosesi yaratabilirler. Aynı zamanda ne zaman bir tred blok sistem çağrısı gerçekleştirirse, kernel işletim için başka bir tred düzenleyebilir

23 Many-to-Many

24 Solaris Threads

25 Solaris Threads Ptred API sini uygular.
Tredlerin yaratılması ve yönetilmesi için API yi içeren bir kütüphane ve kullanıcı tredleri destekler. Tredleri real time olarak düzenler. Kullanıcı ve Kernel tredleri arası LWP lerdir. Her proses en az bir LWP içerir. Tred kütüphanesi, kullanıcı tredlerini proses için olan LWP havuzunda çoklar. Her LWP bir kernel seviyeli trede sahiptir. Her kullanıcı tredi ise kerneldan bağımsızdır.

26 Eğer bir kernel tredi bloke olursa, işlemci başka bir kernel tredini işletebilir. Eğer blok olan tred bir LWP nin bir kısmında çalışıyor ise LWP de blok olmuş olur. Buna bağlı olarak o LWP ye attach edilmiş diğer tredler de blok olmuş olurlar. Eğer bir proses birden çok LWP ye sahipse kernel diğer LWP yi düzenler. Uygulamanın en iyi performans ile çalışıyor olması için LWP sayıları sürekli olarak kontrol edilir. Örneğin bir prosesteki tüm LWP ler blok olmuş ise ve tredler çalışmaya hazır ise, tred kütüphanesi otomatik olarak başka bir LWP yi bekleyen trede attach eder. Aynı şekilde LWP ler uzun süre kullanılmamış ise tred kütüphaneleri bunları silebilirler.

27 Win- Threads Win32 API si microsoft işletim sistemleri için birincil API dir. Bir windows uygulaması her prosesin bir yada daha çok tred içerebileceği birbirinden ayrı prosesleri işletir. Windows one-to-one mimarisini kullanır. Her kullanıcı seviyeli tred uygun bir kernel tredine map edilir. Bundan başka windos bir fiber kütüphanesi de sunar. Bu kütüphane many-to-many fonksiyonu sağlar. Bir prosese ait her tred, prosesin sanal adres alanına erişebilir. Tredin genel bileşenleri: Tred’i belirten tekil bir tred ID İşlemcinin durumunu belirtir bir register set Tred kullanıcı modunda çalışırken kullanılan bir kullanıcı yığını. Benzer olarak her tred aynı zamanda bir kernel yığınına sahiptir. Ve bu yığın tred kernel modunda çalışırken kullanılır. Bir çok run time kütüphane ile kullanılan özel bir depolama alanı ve dinamik link kütüphaneleri (DLL)

28 Processes & Threads Internal Data Structures
Access Token VAD VAD VAD Process Object Virtual Address Space Descriptors Handle Table object object In addition to a private address space and one or more threads, each process has a security identification and a list of open handles to objects such as files, shared memory sections, or one of the synchronization objects such as mutexes, events, or semaphores, as illustrated in this slide. Every process has a security context that is stored in an object called an access token. The process access token contains the security identification and credentials for the process. By default, threads don’t have their own access token, but they can obtain one, thus allowing individual threads to impersonate the security context of another process—including processes running on a remote Windows system—without affecting other threads in the process. (See Chapter 8 for more details on process and thread security.) The virtual address descriptors (VADs) are data structures that the memory manager uses to keep track of the virtual addresses the process is using. These data structures are described in more depth in the Memory Management unit (Book Chapter 7). Thread Thread Thread . . . Access Token

29 Kernel: Thread Priority Levels
31 16 16 “real-time” levels 15 1 15 variable levels Used by zero page thread i Used by idle thread(s)

30 Windows Kernel Priorities

31 Windows Process and Thread Internals
Her process/thread için Data Structures: Executive process block (EPROCESS) Executive thread block (ETHREAD) TEB (Thread environment block) Each Windows process is represented by an executive process (EPROCESS) block. Besides containing many attributes relating to a process, an EPROCESS block contains and points to a number of other related data structures. For example, each process has one or more threads represented by executive thread (ETHREAD) blocks. (Thread data structures are explained in the section “Thread Internals” later in this chapter.) The EPROCESS block and its related data structures exist in system space, with the exception of the process environment block (PEB), which exists in the process address space (because it contains information that is modified by user-mode code). In addition to the EPROCESS block, the Windows subsystem process (Csrss) maintains a parallel structure for each Windows process that executes a Windows program. Also, the kernel-mode part of the Windows subsystem (Win32k.sys) has a per-process data structure that is created the first time a thread calls a Windows USER or GDI function that is implemented in kernel mode.

32 Thread Block ETHREAD (executive thread block )
Create and Exit Time Process ID Thread Start Address Impersonation Information LPC Message Information EPROCESS Access Token KTHREAD Timer Information Pending I/O Requests KTHREAD (Kernel Thread Block) Dispatcher Header Total User Time Total Kernel Time Kernel Stack Information System Service Table Thread Scheduling Information Trap Frame Thread Local Storage Synchronization Information Timer Block and Wait Blocks List of Objects Being Waiting On TEB (Enviroment Block)

33 Thread Block (!thread) Thread ID Process ID Address of system
service dispatch table Address of thread environment block Address of ETHREAD THREAD 83160f60 Cid 9f.3d Teb: 7ffdc000 Win32Thread: e153d2c8 WAIT: (WrUserRequest) UserMode Non-Alertable 808e9d60 SynchronizationEvent Not impersonating Owning Process 81b44880 WaitTime (seconds) Context Switch Count LargeStack UserTime :00: KernelTime :00: Start Address kernel32!BaseProcessStart (0x77e8f268) Win32 Start Address 0x020d9d98 Stack Init f Current f7817bb0 Base f Limit f Call 0 Priority 14 BasePriority 8 PriorityDecrement 6 DecrementCount 13 Kernel stack not resident. ChildEBP RetAddr Args to Child f7817bb0 8008f ntoskrnl!KiSwapThreadExit f7817c50 de0119ec ntoskrnl!KeWaitForSingleObject+0x2a0 f7817cc0 de0123f win32k!xxxSleepThread+0x23c f7817d10 de01f2f win32k!xxxInternalGetMessage+0x504 f7817d80 800bab win32k!NtUserGetMessage+0x58 f7817df0 77d887d ntoskrnl!KiSystemServiceEndAddress+0x4 0012fef user32!GetMessageW+0x30 Thread state Actual thread start address Objects being waited on Lab objective: Using the Kernel Debugger !thread Command The kernel debugger !thread command dumps a subset of the information in the thread data structures. Some key elements of the information the kernel debugger displays can’t be displayed by any utility: internal structure addresses; priority details; stack information; the pending I/O request list; and, for threads in a wait state, the list of objects the thread is waiting for. To display thread information, use either the !process command (which displays all the thread blocks after displaying the process block) or the !thread command to dump a specific thread. The output of the thread information, along with some annotations of key fields, is shown above. Address of user thread function Priority Information Stack trace

34 Thread lifetime Tred işletim sistemine dönene kadar
ExitThread tred tarafından çağrılana kadar TerminateThread tred de işletilene kadar ExitProcess çağrısı yapılana kadar

35 The main Stages Windows follows to create a process
Open EXE and create selection object Creating process Create NT process object Create NT thread object Windows subsystem New process Set up for new process and thread Notify Windows subsystem Final process/image initialization Start execution of the initial thread Start execution at entry point to image Return to caller

36 Linux Threads Proses yaratmak  fork()
Tred yaratmak  clone sistem çağrısı Clone, fork() fonksiyonu gibi iş yapmaktadır, yalnızca prosesin kopyasını yaratmak yerine, ilgili prosesin adres alanını kullanan ayrı bir proses yaratır. Sistemdeki her proses için tekil bir kernel veri yapısı (struct task_struct) mevcuttur. Bu veri yapısı task için veri depolamak yerine diğer veri yapılarına pointer içerir (örn open file list data structure, virtual memory data structure gibi) Fork() çağrıldığında, parent prosesin tüm veri yapılarının bir kopyası ile yeni bir task yaratılır Linux tredler ve prosesler arasında ayrım yapmaz. Clone() çağrısı ile parent ve child arasında paylaşılan veri yapıları aşağıdaki parametrelerin geçirilmesi ile sağlanır.


"BÖLÜM 5 THREADS." indir ppt

Benzer bir sunumlar


Google Reklamları