CS 241 Spring 2007System Programming2/5/07 CS241 © 2006-2007 LA, RHC andYZ, All Rights Reserved1Threads - FinaleLawrence AngraveLecture 92AdministrativeThis weekSMP2Quiz for SMP1Compass self-assessment quizLecture quiz Wed or FridayBook sectionsR & R Chapter 12 (POSIX Threads)p. 409-4463Part 1 - Thread concepts4Practice exam question:List 5 items/resources that are sharedby threads of the same process5List 5 items that are shared by threadsof the same process?address space: code and global variables(“Code section”) (“Data section”)open filessignalstimersprocess IDA thread has its own program counter and stack,but shares a number of resources with its processand other threads of the process:6Thread PackagesKernel thread packagesImplemented and supported at the kernel levelUser-level thread packagesImplemented at the user level7More example exam questions“Illustrate how the threads of a multi-threadedapplication using user-level threads map tokernel-level threads”“Describe 3 advantages & 3 disadvantages ofUser-level threads compared to kernel-levelthreads”8User-level Thread9User Level ThreadsUser-level threads without direct O/S supportThreads are invisible to the kernelSimpler kernel implementationHave lower context-switch overhead compared toK.L.TsCan only use one processor at a timeImplementation dependentCPU-bound threads can block other threads(or) Requires a special library of system calls toprevent blocking10Kernel-level ThreadsKernel can schedule threads in addition toprocesses.Multiple threads of a process can runsimultaneously on multiple CPUs.Synchronization more efficient than for processes(but less than for user-level threads).Kernel-level threads can make blocking I/O callswithout blocking other threads of sameprocess11Kernel-Level Thread12Trade-offs (review)?Kernel thread packagesEach thread can make blocking I/O callsCan run concurrently on multiple processorsThreads in User-levelFast context switchCustomized schedulingSo which one do we choose?13Hybrid Implementations (Solaris) Multiplexing user-level threads onto kernel-level threads14Part 2 POSIX threadsAttributesSchedulingDetachingCancelingrestrictHow many ways can my program exit?15What’s POSIX Got To Do With It?Each OS had it’s own thread library and styleThat made writing multithreaded programs difficult because:you had to learn a new API with each new OSyou had to modify your code with each port to a new OSPOSIX (IEEE 1003.1c-1995) provided a standard known asPthreadsUnix International (UI) threads (Solaris threads) are available onSolaris (which also supports POSIX threads)16Pthreads--- POSIX ThreadsIt is a standard APISupported by most vendorsGeneral concepts applicable to other thread APIs(java threads, NT threads,etc).Low level functionsNo high level constructs17Pthread Operations (review)find out own thread IDpthread selfwait for a threadpthread joinsend a signal to a threadpthread killexit a thread without exiting processpthread exittest two thread IDs for equalitypthread equalset thread to release resourcespthread detachcreate a threadpthread createterminate another threadpthread canceldescriptionPOSIX function18Return Values (review)Most POSIX functions return 0 on success and anonzero error code on failure.They do not set errno but the value returned when anerror occurs has the value that errno would have.19Creating a Thread (review)When a new thread is created it runsconcurrently with the creating process.When creating a thread you indicate whichfunction the thread should execute.20POSIX functions that are not required to be thread-safe.nftwg et pw entendutxentm rand 4 8g et p rotoentendp w entlrand4 8g et p rotob ynum b erendg rentw ctom blocaltim eg et p rotob ynam eencryp tw cstom b slocaleco nvg et o p tecvtunsetenvlg am m alg et netentd rand 4 8tty nam elg am m afg et netb ynam ed lerro rstrto klg am m ag et netb yad d rd irnam estrerrorl6 4 ag et lo g ind b m storesetutxentinet nto ag et hostentdb m op ensetp w enthsearchg etho stb ynam ed b m nextkeysetkeyhd est ro yg et hostb y ad d rd b m f irstkeysetg renthcreateg et g rnamdb m fet chsetenvg m t im eg et g rg idd b m errorread d irg et utxlineg et g rentd b m d eleterandg et utxidg et envd b m clo sep ututxlineg et utxentg et d ated b m clearerrp utenvg et serventg et char unlockedctim ep utchar unlo ckedg et servb y p ortg et c unlo ckedcryp tp utc unlockedg et servb y nam eg cvtcatg etsp tsnam eg et p w uidftwb asenam enl lang infog et p w namfcvtasct im e21Creating a thread with pthreadA thread is created withint 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 storageof the thread id. The third parameter is just the name of the function for the thread torun.The last parameter is a pointer to the arguments.22Restrict KeywordOne of the new features in the recently approvedC standard C99This qualifier can be applied to a data pointer toindicate thatDuring the scope of that pointer declaration, all dataaccessed through it will be accessed only throughthat pointer but not through any other pointer.It enables the compiler to perform certainoptimizations based on the premise that a givenobject cannot be changed through another pointerCan avoid pointer aliasing problem2324The Thread IDpthread_t pthread_self(void)Each thread has an id of type pthread_t.On most systems this is just an integer (like a processID)But it does not have to beA thread can get its ID with pthread_selfCompare two threadsint pthread_equal(thread_t t1, pthread_t t2)25Exiting and CancellationQuestion:If a thread calls exit(), what about other threads in thesame process?“List the conditions that cause a process toterminate?”26Exiting and CancellationQuestion:If a thread calls exit(), what about other threads in thesame process?A process can terminate when:it calls exit directlyone of its threads calls exitit returns from main()it receives a termination signalIn any of these cases, all threads of the processterminate.27ExitingWhen a thread is done, it can return from its firstfunction (the one used by pthread_create) or it cancall pthread_exitvoid pthread_exit(void *value_ptr);Common uses:Return value is often a pointer to the original structor a malloc’d struct (memory must be free’d byjoining
View Full Document