Unix Threads operating systems. User Thread Packages pthread package mach c-threads Sun Solaris3 UI threads Kernel Threads Windows NT, XP operating systems.

Slides:



Advertisements
Similar presentations
Threads Relation to processes Threads exist as subsets of processes Threads share memory and state information within a process Switching between threads.
Advertisements

Copyright ©: Nahrstedt, Angrave, Abdelzaher1 pThreads.
1 Threads. 2 Real Life Example?  Process  “system programming” course  Different from “internet engineering”  Thread  homework, Reading, Self-assessment.
Day 10 Threads. Threads and Processes  Process is seen as two entities Unit of resource allocation (process or task) Unit of dispatch or scheduling (thread.
Threads Lab اللهم علمنا ما ينفعنا،،، وانفعنا بما علمتنا،،، وزدنا علماً
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.
Pthreads Operating Systems Hebrew University of Jerusalem Spring 2004.
8-1 JMH Associates © 2004, All rights reserved Windows Application Development Chapter 10 - Supplement Introduction to Pthreads for Application Portability.
Lecture 18 Threaded Programming CPE 401 / 601 Computer Network Systems slides are modified from Dave Hollinger.
Threads© Dr. Ayman Abdel-Hamid, CS4254 Spring CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid Computer Science Department.
Netprog Threads Programming1 Threads Programming Refs: Chapter 23.
Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Chapter 4: Threads.
Operating Systems Chapter 5 Threads. Benefits Responsiveness Resource Sharing Economy Utilization of MP Architectures.
Introduction to Pthreads. Pthreads Pthreads is a POSIX standard for describing a thread model, it specifies the API and the semantics of the calls. Model.
PRINCIPLES OF OPERATING SYSTEMS Lecture 6: Processes CPSC 457, Spring 2015 May 21, 2015 M. Reza Zakerinasab Department of Computer Science, University.
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.
June-Hyun, Moon Computer Communications LAB., Kwangwoon University Chapter 26 - Threads.
Threads and Thread Control Thread Concepts Pthread Creation and Termination Pthread synchronization Threads and Signals.
Includes slides from course CS194 at UC Berkeley, by prof. Katherine Yelick Shared Memory Programming Pthreads: an overview Ing. Andrea Marongiu
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?
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,
Pthreads.
12/22/ Thread Model for Realizing Concurrency B. Ramamurthy.
Chapter 6 P-Threads. Names The naming convention for a method/function/operation is: – pthread_thing_operation(..) – Where thing is the object used (such.
Threads Dr. Yingwu Zhu. Threaded Applications Web browsers: display and data retrieval Web servers Many others.
Copyright ©: Nahrstedt, Angrave, Abdelzaher
Threads A thread is an alternative model of program execution
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.
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.
回到第一頁 What are threads n Threads are often called "lightweight processes” n In the UNIX environment a thread: u Exists within a process and uses the process.
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.
Lesson One – Creating a thread
Realizing Concurrency using the thread model
Auburn University COMP7330/7336 Advanced Parallel and Distributed Computing Thread Basics Dr. Xiao Qin Auburn University.
Day 12 Threads.
Threads Threads.
Boost String API & Threads
Copyright ©: Nahrstedt, Angrave, Abdelzaher
Thread Programming.
Chapter 2 Processes and Threads Today 2.1 Processes 2.2 Threads
Chapter 4: Threads.
Linux Processes & Threads
Multithreading Tutorial
Principles of Operating Systems Lecture 8
Realizing Concurrency using Posix Threads (pthreads)
Operating Systems Lecture 13.
Realizing Concurrency using the thread model
Multithreading Tutorial
Thread Programming.
Realizing Concurrency using the thread model
Operating System Concepts
Chien-Chung Shen CIS/UD
Multithreading Tutorial
Multithreading Tutorial
Realizing Concurrency using the thread model
Realizing Concurrency using Posix Threads (pthreads)
Realizing Concurrency using the thread model
Programming with Shared Memory
Realizing Concurrency using Posix Threads (pthreads)
Tutorial 4.
Presentation transcript:

Unix Threads operating systems

User Thread Packages pthread package mach c-threads Sun Solaris3 UI threads Kernel Threads Windows NT, XP operating systems

PthreadsPthreads The solution to writing portable, multi- threaded applications is to use POSIX threads. POSIX threads work on Linux, FreeBSD, Solaris, AIX, and other *nix systems. OS/X uses pthreads. They are not shipped with Windows, but pthread packages are available from other vendors. The solution to writing portable, multi- threaded applications is to use POSIX threads. POSIX threads work on Linux, FreeBSD, Solaris, AIX, and other *nix systems. OS/X uses pthreads. They are not shipped with Windows, but pthread packages are available from other vendors. operating systems

Posix Thread Support Prior to POSIX c, there was no standard interface for threads. Each vendor, if they supported threads at all, had their own threads package. POSIX standardized threads in POSIX1003.1c, in June of 1995 Prior to POSIX c, there was no standard interface for threads. Each vendor, if they supported threads at all, had their own threads package. POSIX standardized threads in POSIX1003.1c, in June of 1995 operating systems * Posix Threads are implemented as kernel threads on OS X

Reentrant code When using threads, you must take care that any code you use is reentrant. Reentrant code can be called more than once, perhaps from different threads, without conflicts. Each copy of the code must have its own copy of any variables that it uses, so must not use global or static variables Be careful when using threads, because some system calls are not thread-safe. When using threads, you must take care that any code you use is reentrant. Reentrant code can be called more than once, perhaps from different threads, without conflicts. Each copy of the code must have its own copy of any variables that it uses, so must not use global or static variables Be careful when using threads, because some system calls are not thread-safe. operating systems

Creating a New Thread #include int pthread_create(pthread_t *thread, pthread_att *attr, void *(*start_routine)(void *), void *arg); the thread handle gets stored here returns a 0 if successful otherwise an errno! Note that this differs from the normal Unix standard of returning -1 for an error. thread attributes, usually NULL. the function to begin executing on this thread. It must take a void * as an argument and return a void *. When the function returns, the thread exits. argument given to the thread function. usually a pointer to a struct or an array operating systems

Terminating a Thread #include void pthread_exit(void *retval); this must point to data that exists after the thread terminates! Never point to local data defined in the thread! A thread exits when the thread function returns. Alternatively, the thread can call the pthread_exit function. operating systems

Very Simple Thread Program #include void* printxs (void* unused) // the thread function { while(1) fputc('x', stderr); return NULL; } int main ( ) { pthread_t x_thread; // the thread handle pthread_create (&x_thread, NULL, &printxs, NULL); while(1) fputc('o', stderr); return 0; } pthread_create main thread of execution printxs operating systems thread1

Passing Data to Threads The thread argument is of type void* This allows us to pass a lot of data to a thread by passing a pointer to a struct or an array of data. operating systems

Data Passing Example #include // use this struct to pass parameters to thread function struct char_print_params { char print_char; int number_to_print; } we will declare this structure to pass multiple pieces of data to a thread function. Each thread can have different values.

// the print function … void* char_print (void* params) { struct char_print_params* p; p = (struct char_print_params*) params; int i; for (i = 0; i number_to_print; i++) fputc (p->print_char, stderr); return NULL; } cast the pointer passed to the thread function to a pointer to a char_print_params structure, then use the structure to get at the parameters.

int main ( ) { pthread_t thread1_handle; pthread_t thread2_handle; struct char_print_params thread1_args; struct char_print_params thread2_args; thread1_args.print_char = ‘x’; thread1_args.number_to_print = 3000; pthread_create (&thread1_handle, NULL, &char_print, &thread1_args); thread2_args.print_char = ‘y’; thread2_args.number_to_print = 5000; pthread_create (&thread2_handle, NULL, &char_print, &thread2_args); return 0; } pthread_create print ys print xs main thread

This program has a serious bug … do you know what it is? thread2.c

main will likely exit before either thread finishes. But notice that the thread arguments are pointers to structures declared as local variables in main. When main exits, these pointers are no longer valid! int main ( ) { pthread_t thread1_handle; pthread_t thread2_handle; struct char_print_params thread1_args; struct char_print_params thread2_args; thread1_args.print_char = ‘x’; thread1_args.number_to_print = 3000; pthread_create (&thread1_handle, NULL, &char_print, &thread1_args); thread2_args.print_char = ‘y’; thread2_args.number_to_print = 5000; pthread_create (&thread2_handle, NULL, &char_print, &thread2_args); return 0; }

One solution is to force main to wait until the other two threads are done.

Waiting for a Thread #include int pthread_join(pthread_t th, void **retval); the thread to wait for pointer to the return value. NULL if there is nothing to return. Note that the thread that started the new thread does not necessarily have to be the thread that executes the pthread_join() function. 0 on success or error code.

int main ( ) { pthread_t thread1_handle; pthread_t thread2_handle; struct char_print_params thread1_args; struct char_print_params thread2_args; thread1_args.print_char = ‘x’; thread1_args.number_to_print = 3000; pthread_create (&thread1_handle, NULL, &char_print, &thread1_args); thread2_args.print_char = ‘y’; thread2_args.number_to_print = 5000; pthread_create (&thread2_handle, NULL, &char_print, &thread2_args); pthread_join (thread1_handle, NULL); pthread_join (thread2_handle, NULL); return 0; } no return values thread3.c

Exploiting Shared Memory void *thread_function(void *arg); char message[ ] = “Hello World!”; int main () { int res; // to hold return values pthread_t a_thread; // to keep our thread handle void *thread_result; // to store the return value from the thread thread4.c

res = pthread_create(&a_thread, NULL, &thread_function, (void *)message); if (res != 0) { perror(“Thread creation failed”); exit(1); } thread handle the address of the thread function cast to a void* and pass message to the thread function at this point, two threads are running, if the thread creation step was successful. Each thread now gets its own share of time slices.

printf(“Waiting for the thread to finish…\n”); res = pthread_join(a_thread, &thread_result); if( res != 0) { perror(“Thread join failed”); exit(1); } the pthread_join function puts this thread in a wait state until the thread we just started (a_thread is its handle) finishes. the return value is stored here

now while the first thread is waiting … void thread_function(void *arg) { printf(“thread function running. Argument was %s\n”, (char *)arg); sleep(3); strcpy(message, “Bye!”); pthread_exit(“Thank you for the CPU time”); } print out the argument passed “Hello world!” // sleep for a while change the message. We share the same address space! Could not do this if we used a fork( ). exit, returning this message to the caller

printf(“Thread_join returned, value returned = %s\n”, (char *)thread_result); printf(“Value of message is now %s\n”, message); exit(0); }

Thread Ids Occasionally, it is useful for a sequence of code to determine which thread is running it. pthread_t pthread_self ( );

Comparing Thread IDs Compare two thread IDs with the pthread_equal function. For example, you might check to make sure that a thread ID is not equal to the current thread’s ID, since a thread cannot join itself. if (!pthread_equal (pthread_self( ), other_thread)) pthread_join (other_thread, NULL);

Thread Attributes Thread attributes allow the programmer to fine tune the behavior of individual threads. Initialization Stack Size Stack Address Detach State Scope Inheritance Schedule Policy Schedule Parameters

Detaching a Thread When a thread exits, it does not release its resources unless it is a detached thread, or another thread is waiting with a pthread_join( ).

int pthread_detach(pthread_t thread); if successful returns 0 This thread will release all of its resources when it exits. This thread will not report any status when it exits. This thread is not joinable.