1 Threads. 2 Real Life Example?  Process  “system programming” course  Different from “internet engineering”  Thread  homework, Reading, Self-assessment.

Slides:



Advertisements
Similar presentations
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 pThreads.
Advertisements

Threads By Dr. Yingwu Zhu. Review Multithreading Models Many-to-one One-to-one Many-to-many.
Fork Fork is used to create a child process. Most network servers under Unix are written this way Concurrent server: parent accepts the connection, forks.
Threads Threads are lightweight processes
Pthreads Operating Systems Hebrew University of Jerusalem Spring 2004.
Unix Threads operating systems. User Thread Packages pthread package mach c-threads Sun Solaris3 UI threads Kernel Threads Windows NT, XP operating systems.
Threads© Dr. Ayman Abdel-Hamid, CS4254 Spring CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid Computer Science Department.
PRINCIPLES OF OPERATING SYSTEMS Lecture 6: Processes CPSC 457, Spring 2015 May 21, 2015 M. Reza Zakerinasab Department of Computer Science, University.
1 Threads Chapter 11 from the book: Inter-process Communications in Linux: The Nooks & Crannies by John Shapley Gray Publisher: Prentice Hall Pub Date:
10/16/ Realizing Concurrency using the thread model B. Ramamurthy.
B. RAMAMURTHY 10/24/ Realizing Concurrency using the thread model.
Operating Systems CMPSC 473 Multi-threading models Tutorial on pthreads Lecture 10: September Instructor: Bhuvan Urgaonkar.
Threads and Thread Control Thread Concepts Pthread Creation and Termination Pthread synchronization Threads and Signals.
POSIX Threads Programming Operating Systems. Processes and Threads In shared memory multiprocessor architectures, such as SMPs, threads can be used to.
1 Threads Chapter 11 from the book: Inter-process Communications in Linux: The Nooks & Crannies by John Shapley Gray Publisher: Prentice Hall Pub Date:
1 Threads. 2 Processes versus Threads 3 Why Threads? Processes do not share resources very well Why? Process context switching cost is very high Why?
Source: Operating System Concepts by Silberschatz, Galvin and Gagne.
CS333 Intro to Operating Systems Jonathan Walpole.
Professor: Shu-Ching Chen TA: Samira Pouyanfar.  An independent stream of instructions that can be scheduled to run  A path of execution int a, b; int.
Pthreads: A shared memory programming model
Threads CSCE Thread Motivation Processes are expensive to create. Context switch between processes is expensive Communication between processes.
S -1 Posix Threads. S -2 Thread Concepts Threads are "lightweight processes" –10 to 100 times faster than fork() Threads share: –process instructions,
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 Processes and Threads.
1 Pthread Programming CIS450 Winter 2003 Professor Jinhua Guo.
Pthreads.
12/22/ Thread Model for Realizing Concurrency B. Ramamurthy.
Unix Internals Concurrent Programming. Unix Processes Processes contain information about program resources and program execution state, including: Process.
Copyright ©: Nahrstedt, Angrave, Abdelzaher
Thread S04, Recitation, Section A Thread Memory Model Thread Interfaces (System Calls) Thread Safety (Pitfalls of Using Thread) Racing Semaphore.
POSIX Threads Loren Stroup EEL 6897 Software Development for R-T Engineering Systems.
NCHU System & Network Lab Lab #6 Thread Management Operating System Lab.
Thread Basic Thread operations include thread creation, termination, synchronization, data management Threads in the same process share:  Process address.
POSIX THREADS. What is a thread? Multiple stands of execution in a single program are called threads. In other words, a thread is a sequence of control.
2.2 Threads  Process: address space + code execution  There is no law that states that a process cannot have more than one “line” of execution.  Threads:
B. RAMAMURTHY 5/10/2013 Amrita-UB-MSES Realizing Concurrency using the thread model.
7/9/ Realizing Concurrency using Posix Threads (pthreads) B. Ramamurthy.
Tutorial 4. In this tutorial session we’ll see Threads.
A thread is a basic unit of CPU utilization within a process Each thread has its own – thread ID – program counter – register set – stack It shares the.
Realizing Concurrency using the thread model
Threads Some of these slides were originally made by Dr. Roger deBry. They include text, figures, and information from this class’s textbook, Operating.
Realizing Concurrency using the thread model
Threads in C Caryl Rahn.
Threads Threads.
Boost String API & Threads
Copyright ©: Nahrstedt, Angrave, Abdelzaher
CS399 New Beginnings Jonathan Walpole.
Thread Programming.
Chapter 4: Threads.
Multithreading Tutorial
Principles of Operating Systems Lecture 8
Multithreading Tutorial
Realizing Concurrency using Posix Threads (pthreads)
Operating Systems Lecture 13.
Realizing Concurrency using the thread model
Lecture 8: POSIX Threads
Multithreading Tutorial
Thread Programming.
Realizing Concurrency using the thread model
Pthread Prof. Ikjun Yeom TA – Mugyo
Operating System Concepts
Multithreading Tutorial
Multithreading Tutorial
Realizing Concurrency using the thread model
Realizing Concurrency using Posix Threads (pthreads)
Realizing Concurrency using the thread model
Lecture 9: POSIX Threads Cont.
Realizing Concurrency using Posix Threads (pthreads)
Lecture 8: POSIX Threads
Tutorial 4.
Concurrency and Threading: Introduction
Presentation transcript:

1 Threads

2 Real Life Example?  Process  “system programming” course  Different from “internet engineering”  Thread  homework, Reading, Self-assessment quiz  Each is a different “execution”  But all share  Content  Textbook  Personnel (TAs, instructors)  Affect each other

3 Review: threads vs. processes (created with fork) Property Processes created with fork Threads of a processOrdinary function calls variablesget copies of all variablesshare global variables IDsget new process IDs share the same process ID but have unique thread ID share the same process ID (and thread ID) Communication Must explicitly communicate, e.g.pipes or use small integer return value May communicate with return value or shared variables if done carefully May communicate with return value or shared variables (don't have to be careful) Parallelism (one CPU) Concurrent Sequential Parallelism (multiple CPUs) May be executed simultaneously Kernel threads may be executed simultaneously Sequential

4 Thread components  A thread has its own program counter and stack, but shares a number of resources with its process and other threads of the process:  address space: code and global variables  open files  semaphores  signals  timers  process ID  Thread specific resource:  Thread ID  Program counter  Register set  Stack space  Signal mask (later…)

5 Thread vs. Process Each thread execute separately Threads in the same process share resources No protection among threads!!

6 Normal function call

7 Threaded function call

8 Designing Threaded Programs Thread candidates? Discrete, independent tasks which can execute concurrently E.g. if routine1 and routine2 can be interchanged, interleaved and/or overlapped in real time, they are candidates for threading

9 Common Multi-thread Software Architectures  Manager/worker  a single thread, the manager assigns work to other threads, the workers.  Typically, the manager handles all input and parcels out work to the other tasks  Pipeline:  a task is broken into a series of sub-operations, each of which is handled in series, but concurrently, by a different thread.  An automobile assembly line best describes this model  Peer  similar to the manager/worker model, but after the main thread creates other threads, it participates in the work

10 Pthreads--- POSIX Threads  It is a standard API  Supported by most vendors  General concepts applicable to other thread APIs (java threads, NT threads,etc).  Low level functions

11 Pthread Operations POSIX functiondescription pthread_create create a thread pthread_detach set thread to release resources pthread_equal test two thread IDs for equality pthread_exit exit a thread without exiting process pthread_kill send a signal to a thread pthread_join wait for a thread pthread_self find out own thread ID

12 pthread_* return values  Unlike most POSIX functions, they do not set errno but the value returned when an error occurs has the value that errno would have.  None of the POSIX thread functions ever return the error EINTR.

13 Example program #include void *threadex(void *); int main() { pthread_t tid; /* stores the new thread ID */ pthread_create(&tid, NULL, threadex, NULL); /*create a new thread*/ pthread_join(tid, NULL); /*main thread waits for other thread to terminate */ return 0; /* main thread exits */ } void *threadex(void *arg) /*thread routine*/ { int i; for (i=0; i<5; i++) fprintf(stderr, `Hello, world! \n''); return NULL; }

14 Creating a thread with pthread  A thread is created with int pthread_create( pthread_t *restrict thread, const pthread_attr_t *restrict attr, void *(*start_routine)(void *), void *restrict arg);  The creating process (or thread) must provide a location for storage of the thread id.  The third parameter is just the name of the function for the thread to run.  The last parameter is a pointer to the arguments.

15 Restrict Keyword  One of the new features in the recently approved C standard C99  This qualifier can be applied to a data pointer to indicate that  During the scope of that pointer declaration, all data accessed through it will be accessed only through that pointer but not through any other pointer.  It enables the compiler to perform certain optimizations based on the premise that a given object cannot be changed through another pointer  emystifying_the_restrict_keyw.html emystifying_the_restrict_keyw.html

16 The Thread ID pthread_t pthread_self(void)  Each thread has an id of type pthread_t.  On most systems this is just an integer (like a process ID)  But it does not have to be  A thread can get its ID with pthread_self  Compare two threads  int pthread_equal(thread_t t1, pthread_t t2)

17 Exiting and Cancellation  Question:  If a thread calls exit(), what about other threads in the same process?  A process can terminate when:  it calls exit directly  one of its threads calls exit  it returns from main()  it receives a termination signal  In any of these cases, all threads of the process terminate.

18 Exiting  When a thread is done, it can return from its first function (the one used by pthread_create) or it can call pthread_exit void pthread_exit(void *value_ptr);

19 Cancel that thread!  One thread can request that another exit with pthread_cancel int pthread_cancel(pthread_t thread);  The pthread_cancel returns after making the request.  A successful return does not mean that the target thread has terminated or even that it eventually will terminate as a result of the request

20 Thread Attributes  Create an attribute object (initialize it with default properties)  Modify the properties of the attribute object  Create a thread using the attribute object  The attribute object can be changed or reused without affecting the thread  The attribute object affects the thread only at the time of thread creation

21 Attribute Initialization and Deletion Initialize or destroy an attribute with: int pthread_attr_destroy(pthread_attr_t *attr); int pthread_attr_init(pthread_attr_t *attr);

22 Example: Create a detached thread int e, fd; pthread_attr_t tattr; pthread_t tid; if(e = pthread_attr_init(&tattr)) fprintf(stderr, "Failed to create attribute object: %s\n", strerror(e)); else if(e = pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED)) fprintf(stderr, "Failed to set attribute state to detached: %s\n", strerror(e)); else if(e = pthread_create(&tid, &tattr, data, &fd)) fprintf(stderr, "Failed to create thread: %s\n", strerror(e));

23 Settable properties of thread attributes propertyfunction attribute objects pthread_attr_destroy pthread_attr_init detach state pthread_attr_getdetachstate pthread_attr_setdetachstate stack pthread_attr_getguardsize pthread_attr_setguardsize pthread_attr_getstack pthread_attr_setstack scheduling pthread_attr_getinheritsched pthread_attr_setinheritsched pthread_attr_getschedparam pthread_attr_setschedparam pthread_attr_getschedpolicy pthread_attr_setschedpolicy pthread_attr_getscope pthread_attr_setscope

24 Thread Detach & Join  Call pthread_join() or pthread_detach() for every thread that is created joinable  so that the system can reclaim all resources associated with the thread  Failure to join or to detach threads  memory and other resource leaks until the process ends

25 Detaching a Thread int pthread_detach(pthread_t threadid);  Indicate that system resources for the specified thread should be reclaimed when the thread ends  If the thread is already ended, resources are reclaimed immediately  This routine does not cause the thread to end  Threads are detached  after a pthread_detach() call  after a pthread_join() call  if a thread terminates and the PTHREAD_CREATE_DETACHED attribute was set on creation

26 How to make a thread detached void *processfd(void *arg); int error; int fd pthread_t tid; if (error = pthread_create(&tid, NULL, processfd, &fd)) { fprintf(stderr, "Failed to create thread: %s\n", strerror(error)); } else if (error = pthread_detach(tid)){ fprintf(stderr, "Failed to detach thread: %s\n", strerror(error)); }

27 How a thread can detach itself void *runnger(void *arg) { … if (!pthread_detach( pthread_self()) ) return NULL; … }

28 “Wating” on a Thread: pthread_join() int pthread_join(pthread_t thread, void** retval);  pthread_join() is a blocking call on non-detached threads  It indicates that the caller wishes to block until the thread being joined exits  You cannot join on a detached thread, only non-detached threads

29 Pthread_join int error; int *exitcodep; pthread_t tid; if (error = pthread_join(tid, &exitcodep)){ fprintf(stderr, "Failed to join thread: %s\n", strerror(error)); } else { fprintf(stderr, "The exit code was %d\n", *exitcodep); }