Multi-Thread Programming. Vincent Liu MDE GPE-EA Sun Microsystems Inc. What in this topic. Basics about multi-threaded Program Solaris's thread model Synchranization mechanism Lock Contention How to measure a MT program's scalability on Solaris Some tools at our command on Solaris
An Image/Link below is provided (as is) to download presentation
Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.Content is provided to you AS IS for your information and personal use only.Download presentation by click this link.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.During download, if you can't get a presentation, the file might be deleted by the publisher.
What in this topic • Basics about multi-threaded Program • Solaris's thread model • Synchranization mechanism • Lock Contention • How to measure a MT program's scalability on Solaris • Some tools at our command on Solaris • Improve MT program's performance
Introduction to Multithreading • Process, Thread and LWP • Which Applications Benefit? • When Not to Use Threads • Thread Standard
What Is a Thread? • An independent flow of control in a program • A “virtual” central processing unit(CPU) • Thread share the address space and Process Structure, with its own stack, TCB, KTCB • Traditional Process • MultiThreaded process with only one thread
Thread vs. Process • Thread : high degree of parallelism on multiprocessor systems • Kernel resource consumed ( create, schedule, etc) • Thread: lightweight • Process: heavyweight • Information sharing • Thread : share process address space • Process: IPC
Single LevelThreads Model • The default model in Solaris 9 and 10 • All user threads bound to LWPs • Kernel level scheduling • – No more libthread.so scheduler • More expensive thread create/destroy,Synchronization • More responsive scheduling, synchronization
Which Applications Benefit? • Threads can : • Simplify program structure • Improve throughput • Improve responsiveness • Minimize system resource usage • Simplify realtime applications
When Not to Use Threads • For compute-bound threads on a uniprocessor. • For threads that execute very short tasks • When there is nothing to run concurrently • For multithreaded applications that are more difficult to design and debug than single-threaded applications.
Thread Interfaces Two International standards: • POSIX • Solaris 2.5+, HP-UX 10.30+, Digital Unix 4.0+ • IRIX 6.2+, VMS, AS/400, AIX 4.1+ • UI Thread • Solaris 2.2+, UnixWare
POSIX Thread APIs int pthread_create(&tid, &attr, func, arg ); void pthread_exit(status); int pthread_join(tid, &status); pthread_t pthread_self(); int pthread_equal(tid1, tid2); int pthread_cancel(tid); void sched_yield();
Waiting for a Thread to Exit t1 • “Undetached” threads must be joined and may return a status value • “Detached” threads cannot be joined and cannot return a status value pthread_join(t2) pthread_exit(status) t2
Why use Synchronization • Unsynchronized Shared data is a formula of disaster Thread 1 Thread 2 temp = your.bankbalance; dividend = temp * interestrate; newbanlance = dividend + temp; your.bankbalance += deposit ; your.bankbalance = newbalance;
All shared Data Must Be Locked • Good programmers protect all usage of shared data with locks lock(M); ….. unlock(M); lock(M); ……. unlock(M); Shared data
Synchronization Variables • Used to protect shared resource • Mutex exclusin locks • Used to determine when a thread should run • Counting Semaphores • Condition variables
Mutexes • The blocked thread might not get the mutex • Typical lock/unlock time: one cycle • Critical sections should be as short as possible • Non-critical sections are usually much longer typically
Semaphores Count 0 Sleepers • sem_wait: decrease the count if non-zero; otherwise wait until others execute sem_post • sem_post: increase count by 1, and wakeup sleepers if exists • sem_init : semaphore initialization t1 t3
EINTR • Semaphore can be interrupted by signals, sem_wait can return without decreasing the value while(sem_wait(&s) = = EINTR ) {<probably do nothing>} do_thing;
Avoiding Deadlocks • Deadlocks can always be avoided • You can establish a hierachy • Use a static analysis program(for example lock_lint) to scan your code for hierarchy violations • Use trylock primitive pthread_mutex_lock(&m2); … if (EBUSY==pthread_mutex_trylock(&m1)) { pthread_mutex_unlock(&m2); pthread_mutex_lock(&m1); pthread_muetx_lock(&m2); } do_real_work();
Advanced Topic • Thread Specific Data • Unix Signals • Advanced scheduling • MT-Safe library
Why TSD is needed • Sometimes it is useful to have a global variable which is local to a thread Thread 1 Thread 2 err = read(..); err = ioctl(…); if ( err ) if(err) printf(“%d\n”, errno); printf(“%d\n”, errno);
TSD Destructors • When a thread exits, it first sets the value of each TSD element to NULL, then calls the destructor on what the value was • If you delete a key, the destructor functions will not run, you must deal with it yourself
Advanced Topic • Thread Specific Data • Unix Signals • Advanced scheduling • MT-Safe library
Three uses of Signals • Synchronous signals for Error reporting • SIGFPE, SIGSEGV, SIGBUS, etc • Asynchronous signals for Situation reporting • Asynchronous signals for Interruption • SIGKILL, SIGALRM, SIGSTOP, etc
POSIX Signal Model ? library’s signal handler routines Thread signal mask Signal dispatch table signal
Dedicated Signal Handling Thread • A multithreaded program can create one or more thread dedicated to perform signal handling for whose process by using sigwait pthread_create( &p, &attr, handler, arg ); …. void * handler ( void * arg ){ while (1){ sigwait( & sigset , &sig); …… } }
POSIX Signal API • pthread_sigmask( ) • pthread_kill( ) • sigwait • sigset or sigaction
HOL about Signal • 1. Install signal Handler • 2. In MT, all thread share one handler. • 3. setup different sigmask to direct signal delivery
Advanced Topic • Thread Specific Data • Unix Signals • Advanced scheduling • MT-Safe library
Compiling—s10-no flag needed POSIX cc [flags] file -D_POSIX_C_SOURCE=199506L [-lposix4] -lpthread cc [flags] file -D_REENTRANT -D_POSIX_C_SOURCE=199506L [-lposix4] -lthread Mixed usage Choose semantics cc [flags] file -D_REENTRANT [-lposix4] -lthread UI
Some commands to Observe • Use prstat(1) and ps(1) to monitor running processes and threads • mpstat(1) to monitor context switch rates and thread migrations • dispadmin(1M) to examine and change dispatch table parameters • User priocntl(1) to change scheduling classes and priorities