pthreads 1 Announcement Reminder: SMP1 due today Reminder: Please keep up with the reading assignments (see class webpage) 2 1
Thread Packages Kernel thread packages Implemented and supported at kernel level User-level thread packages Implemented at user level 3 Implementing Threads in User Space (Old Linux) A user-level threads package 4 2
User-level Threads 5 User-level Threads Advantages Fast Context Switching: User level threads are implemented using user level thread libraries, rather than system calls, hence no call to OS and no interrupts to kernel When a thread is finished running for the moment, it can call thread_yield. This instruction (a) saves the thread information in the thread table, and (b) calls the thread scheduler to pick another thread to run. The procedure that saves the local thread state and the scheduler are local procedures, hence no trap to kernel, no context switch, no memory switch, and this makes the thread scheduling very fast. Customized Scheduling 6 3
Kernel-level Threads Kernel can schedule threads in addition to processes. Multiple threads of a process can run simultaneously on multiple CPUs. Synchronization more efficient than for processes (but less than for user-level threads). Kernel-level threads can make blocking I/O calls without blocking other threads of same process 7 Trade-offs? Kernel thread packages Each thread can make blocking I/O calls Can run concurrently on multiple processors Threads in User-level Fast context switch Customized scheduling 8 4
Hybrid Implementations (Solaris) Multiplexing user-level threads onto kernel-level threads 9 Pthread Operations (review) POSIX function pthread_cancel pthread_create pthread_detach pthread_equal pthread_exit pthread_kill pthread_join pthread_self description terminate another thread create a thread set thread to release resources test two thread IDs for equality exit a thread without exiting process send a signal to a thread wait for a thread find out own thread ID 10 5
Creating a Thread When a new thread is created it runs concurrently with the creating process. When creating a thread you indicate which function the thread should execute. 11 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. 12 6
The 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 Can avoid pointer aliasing problem 13 Example 1: Thread Creation #include <pthread.h> #include <stdio.h> #define NUM_THREADS 5 void *PrintHello(void *threadid) { int tid; tid = (int)threadid; printf("hello World! It's me, thread #%d!\n", tid); pthread_exit(null); int main (int argc, char *argv[]) { pthread_t threads[num_threads]; int rc, t; for(t=0; t<num_threads; t++){ printf("in main: creating thread %d\n", t); rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t); if (rc) { printf("error code is %d\n", rc); exit(-1); pthread_exit(null); 14 7
Example 2: Passing Parameters to a Thread #include <pthread.h> #include <stdio.h> #include <stdlib.h> #define NUM_THREADS 5 void *PrintHello(void *ptr) { char *filename; int j; filename = (char *) ptr; while (1) { printf("hello World! It's me, thread %s!\n", filename); for (j=1; j++; j<500); pthread_exit(null); 15 Example 2: Passing Parameters to a Thread int main (int argc, char *argv[]) { pthread_t thread[100]; int err_code, i=0; char *filename; printf ("Enter thread name at any time to create thread\n"); while (1) { filename = (char *) malloc (80*sizeof(char)); scanf ("%s", filename); printf("in main: creating thread %d\n", i); err_code = pthread_create(&thread[i], NULL, PrintHello, (void *)filename); if (err_code){ printf("error code is %d\n", err_code); exit(-1); else i++; pthread_exit(null); 16 8
Example 3: Files void *PrintHello(void *ptr) { FILE *file; char *filename; char textline[100]; int j; filename = (char *) ptr; printf("hello World! Opening %s!\n", filename); file = fopen(filename, "r"); if (file!= NULL) { while(fscanf(file, "%s\n", textline)!= EOF) printf ("%s\n", textline); fclose(file); 17 Exiting and Cancellation Question: If a thread calls exit(), what about other threads in the same process? When does a process terminate? 18 9
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. 19 Thread Exit 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); Common uses: Return value is often a pointer to the original struct or a malloc d struct (memory must be free d by joining thread) Use the heap not the stack!!! 20 10
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. 21 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 object can be changed or reused without affecting the thread The attribute object affects the thread only at the time of thread creation 22 11
Settable Properties of Thread Attributes property attribute objects detach state stack scheduling function pthread_attr_destroy pthread_attr_init pthread_attr_getdetachstate pthread_attr_setdetachstate pthread_attr_getguardsize pthread_attr_setguardsize pthread_attr_getstack pthread_attr_setstack pthread_attr_getinheritsched pthread_attr_setinheritsched pthread_attr_getschedparam pthread_attr_setschedparam pthread_attr_getschedpolicy pthread_attr_setschedpolicy pthread_attr_getscope pthread_attr_setscope 23 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)); 24 12
Zombies, 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 A detached thread s thread ID is undetermined 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 13
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 14
Waiting on a Thread: pthread_join() int pthread_join(pthread_t thread, void** retval); pthread_join() is a blocking call on nondetached 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 (detaching means you are NOT interested in knowing about the threads exit) 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); 30 15
Thread scheduling int pthread_attr_getscope(const pthread_attr_t *restrict attr, int *restrict contentionscope); int pthread_attr_setscope(pthread_attr_t *attr, int contentionscope); The contentionscope can be PTHREAD_SCOPE_PROCESS or PTHREAD_SCOPE_SYSTEM. The scope determines whether the thread competes with other threads of the process or with other processes in the system. 31 Create a thread that contends with other processes pthread_attr_init(&tattr)) pthread_attr_setscope(&tattr, PTHREAD_SCOPE_SYSTEM)) thread_create(&tid, &tattr, myfunction, &myptr)) 32 16