systems programming
play

Systems programming Thread management (Cont.) Most of the slides in - PowerPoint PPT Presentation

Systems programming Thread management (Cont.) Most of the slides in this lecture are either from or adapted from the slides provided by Dr. Ahmad Barghash Creation of Unix processes vs. Pthreads Example of Pthreads #include <pthread.h>


  1. Systems programming Thread management (Cont.) Most of the slides in this lecture are either from or adapted from the slides provided by Dr. Ahmad Barghash

  2. Creation of Unix processes vs. Pthreads

  3. Example of Pthreads #include <pthread.h> #include <stdio.h> void *PrintHello(void * id){ printf (“Thread %d: Hello World! \n", id); } void main (){ pthread_t thread0, thread1; pthread_create(&thread0, NULL, PrintHello, (void *) 0); pthread_create(&thread1, NULL, PrintHello, (void *) 1); }

  4. Example of Pthreads with join #include <pthread.h> #include <stdio.h> void *PrintHello(void * id){ printf (“Hello from thread %d \n", id); } void main (){ pthread_t thread0, thread1; pthread_create(&thread0, NULL, PrintHello, (void *) 0); pthread_create(&thread1, NULL, PrintHello, (void *) 1); pthread_join(thread0, NULL); pthread_join(thread1, NULL); }

  5. Compiling a Pthread program gcc −g −Wall −o hello hello.c −lpthread Linking the Pthreads library

  6. Running a Pthreads program ./hello Hello from thread 1 Hello from thread 0 ./hello Hello from thread 0 Hello from thread 1

  7. Terminating Threads • There are several ways in which a Pthread may be terminated: • The thread returns from its starting routine • (the main routine for the initial thread). • The thread makes a call to the pthread_exit() subroutine. • The thread is canceled by another thread via the pthread_cancel() routine • The entire process is terminated due to a call to either the exec() or exit() subroutines.

  8. pthread_exit() - terminate calling thread Description: terminates running a thread. Syntax: void pthread_exit(void *value_ptr);

  9. pthread_exit() -- Example

  10. pthread_self() • The pthread_self() function returns the ID of the thread in which it is invoked. Syntax: pthread_t pthread_self(void);

  11. pthread_self() -- Example

  12. pthread_equal() () • The pthread_equal() function compares two thread identifiers. It return ‘0’ and non zero value. If it is equal then return non zero value else return 0. Syntax: int pthread_equal (pthread_t t1, pthread_t t2);

  13. () – Example 1 pthread_equal()

  14. () – Example 2 pthread_equal()

  15. How about if if th the main th thread uses pthread_exit not pthread_jo join? By having main() explicitly call pthread_exit() as the last thing it does, main() will block and be kept alive to support the threads it created until they are done. for(t=0;t < NUM_THREADS; t++) { pthread_join( threads[t], NULL); }

  16. Similar to previous but with incorrect parameters

  17. pthread_cancel() () • The pthread_cancel() function cancels a particular thread using thread id. This function send a cancellation request to the thread. • Syntax: int pthread_cancel(pthread_t thread);

  18. Thread Detach & Jo Join • Call pthread_join () or pthread_detach () for every thread that is created, so that the system can release all resources associated with the thread. • Failure to join or to detach threads → memory and other resource leaks until the process ends.

  19. Detaching a T Thread • Syntax: int pthread_detach(pthread_t threadid); • Description: Indicate that system resources for the specified thread should be release when the thread ends • If the thread is already ended, resources are release immediately • This routine does not cause the thread to end • Threads are detached • after a pthread_detach() call • after a pthread_join() call

  20. 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)); }

  21. Pt Pthread Operations (r (review) function description pthread_cancel terminate another thread 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_join wait for a thread pthread_self find out own thread ID

  22. Thread Creation (r (review) One obj On bject t for pthread.h eac ach thread ad. pthread_t int pthread_create ( pthread_t* thread_p /* out */ , const pthread_attr_t* attr_p /* in */ , void* (*start_routine ) ( void ) /* in */ , void* arg_p /* in */ ) ;

  23. In all the previous examples in which we used pthread_create , we passed in a null Thread Attributes pointer instead of passing in a pointer to a pthread_attr_t structure • 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 #include <pthread.h> int pthread_attr_init(pthread_attr_t *attr); int pthread_attr_destroy(pthread_attr_t *attr);

  24. Settable Properties of Thread Attributes property function pthread_attr_destroy attribute objects 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

  25. Example of creating a thread with none- default attributes: “a thread of a attribute of contending other processes” #include <pthread.h> • The contention scope can be PTHREAD_SCOPE_PROCESS or PTHREAD_SCOPE_SYSTEM. pthread_t tid; • The scope determines whether the int pthread_attr_setscope(pthread_attr_t *attr, int void * myfunction(void *); contentionscope); • thread competes with other threads of the void *myptr; process or with other processes in the system. pthread_attr_t tattr; pthread_attr_init( &tattr ); pthread_attr_setscope( &tattr, PTHREAD_SCOPE_SYSTEM ); thread_create( &tid, &tattr, myfunction, &myptr );

  26. Multiplication of f Matrix using threads

  27. Mult ltiplication of f Matrix usin ing threads (p (part 1 of f code)

  28. Mult ltiplication of f Matrix usin ing threads (p (part 2 of f code)

  29. An example of Thread synchronization Problem A global Variable If proper synchronization techniques are NOT applied, it may cause a RACE CONDITION where the values of variables may be unpredictable and vary depending on the timings of context switches of the processes or threads.

  30. Race Condition Example int s = 0; Thread 1 Thread 0 for i = 0, n/2-1 for i = n/2, n-1 s = s + f(A[i]) s = s + f(A[i]) • Also called critical section problem. • A race condition or data race occurs when: - two processors ( or two threads ) access the same variable, and at least one does a write. - The accesses are concurrent ( not synchronized ) so they could happen simultaneously

  31. Mutex = Mutual Exclusion One of the primary means of implementing thread synchronization and for protecting shared data when multiple writes occur. Thread Mutex Acts like a lock protecting access to a shared data resource Only one thread can lock (or own) a mutex variable at any given time.

  32. Thread Mutex (Cont.) • A typical sequence in the use of a mutex is as follows: 1. Create and initialize a mutex variable 2. Several threads attempt to lock the mutex 3. Only one succeeds and that thread owns the mutex 4. The owner thread performs some set of actions 5. The owner unlocks the mutex 6. Another thread acquires the mutex and repeats the process 7. Finally the mutex is destroyed

  33. Thread Mutex – Basic Operations int pthread_mutex_init(pthread_mutex_t *mutex, pthread_mutexattr_t *attr) • Initializes a mutex variable (mutex) with some attributes (attr). • attributes are usually NULL. int pthread_mutex_lock(pthread_mutex_t *mutex) Indivisibly waits for mutex to be unlocked and then locks it. int pthread_mutex_unlock(pthread_mutex_t *mutex) Unlocks a mutex.

  34. Threads summary ry • Threads provide a mechanism for writing concurrent programs. • Threads are growing in popularity • Somewhat cheaper than processes. • Easy to share data between threads. • However, the ease of sharing has a cost: • Easy to introduce subtle synchronization errors. • Tread carefully with threads! • For more info: • D. Butenhof , “Programming with Posix Threads”, Addison -Wesley, 1997.

Recommend


More recommend