DOC PREVIEW
U of I CS 498 - Pthreads

This preview shows page 1-2-3-27-28-29 out of 29 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

University of Illinois at Urbana-ChampaignPthreadsCS 498: Compiler OptimizationsFall 2006Threads vs. processes (created with fork)SequentialKernel threads may beexecuted simultaneouslyMay be executedsimultaneouslyParallelism(multiple CPUs)SequentialConcurrentConcurrentParallelism (oneCPU)May communicate withreturn valueor shared variables(don't have to be careful)May communicate with returnvalueor shared variablesif done carefullyMust explicitlycommunicate, e.g.pipesor use small integerreturn valueCommunicationshare the same processID (and thread ID)share the same process ID buthave unique thread IDget new process IDsIDsshare global variablesshare global variablesget copies of allvariablesvariablesOrdinary function callsThreads of a processProcessescreated with !"#$PropertyThread components• address space: code and global variables• open files• signals• timers• process IDA thread has its own program counter and stack,but shares a number of resources with its processand other threads of the process:Pthreads--- POSIX Threads• Pthreads: P from POSIX (Portable Operating SystemInterface)• It is a standard API– Supported by most vendors– General concepts applicable to other thread APIs(java threads, NT threads,etc).• Low level functions– No high level constructsWhat’s POSIX Got To Do With It?• Each OS had it’s own thread library and style• That made writing multithreaded programs difficultbecause:– you had to learn a new API with each new OS– you had to modify your code with each port to anew OS• POSIX (IEEE 1003.1c-1995) provided a standardknown as Pthreads• Unix International (UI) threads (Solaris threads) areavailable on Solaris (which also supports POSIXthreads)Pthread Operationsfind out own thread ID%&'#()* + ,(-!wait for a thread%&'#()*+ ."/0send a signal to a thread%&'#()*+ $/--exit a thread without exitingprocess%&'#()*+ (1/&test two thread IDs for equality%&'#()*+ (2 3)-set thread to release resources%&'#()*+ * (&)4'create a thread%&'#()*+ 4#()&(terminate another thread%&'#()*+ 4)04(-descriptionPOSIX functionReturn Values• 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.Creating a Thread• When a new thread is created it runs concurrently withthe creating process.• When creating a thread you indicate which function thethread should execute.Normal function callThreaded function callCreating a threadA thread is created with pthread_createint pthread_create(pthread_t *thread_id, const pthread_attr_t *attr, void *(*start_routine)(void *),void *args );! Thread ID - Calling thread must provide location for this! Thread attributes - NULL pointer indicates default attributes! Function for thread to run! ArgumentsExample thread creationmain(void){ pthread_t thread1, thread2; pthread_create(&thread1, NULL, (void *) do_one_thing, (void *) &r1); pthread_create(&thread2, NULL, (void *) do_another_thing, (void *) &r2);pthread_join(thread1, NULL); pthread_join(thread2, NULL); return 0;}Creating a threadA thread is created withint pthread_create( pthread_t *restrict thread, const pthread_attr_t *restrict attr, void *(*start_routine)(void *), void *restrict arg);Restrict Keyword• One of the new features in the recentlyapproved C standard C99• This qualifier can be applied to a data pointer toindicate that– During 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 pointer• Can avoid pointer aliasing problemThreaded Function Call Detail• A function that is used as a thread must have a specialformat.– It takes a single parameter of type pointer to void and returns apointer to void.• The parameter type allows any pointer to be passed.• This can point to a structure, so in effect, the function can use anynumber of parameters.The 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 be• A thread can get its ID with pthread_self• Compare two threads– int pthread_equal(pthread_t t1, pthread_t t2)Joining Threads• Suspends caller until specified thread exits– Similar to waitpid for processes• Good practice – call pthread_detach orpthread_join for every thread• pthread_join gets value passed to pthread_exitby terminating threadJoining Threads void *copyfilemalloc(void *arg); char *bytesptr = (char *) malloc(MAX_BYTES); pthread_t tid = -1; if (((fds[0] = open(argv[1], READ_FLAGS)) == -1) || ((fds[1] = open(argv[2], WRITE_FLAGS, PERMS)) == -1)) { perror("Failed to open the files"); return 1; } if (error = pthread_create(&tid, NULL, copyfilemalloc, (void *)fds)) { fprintf(stderr, "Failed to create thread: %s\n", strerror(error)); return 1; } if (error = pthread_join(tid, (void **)&bytesptr)) { fprintf(stderr, "Failed to join thread: %s\n", strerror(error)); return 1; }Thread Detach & Join• Call pthread_join() or pthread_detach() for everythread that is created joinable– so that the system can reclaim all resourcesassociated with the thread• Failure to join or to detach threads "memory and otherresource leaks until the process endsDetaching a Threadint pthread_detach(pthread_t threadid);• Indicate that system resources for the specified threadshould be reclaimed when the thread ends– If the thread is already ended, resources are reclaimedimmediately– 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 thePTHREAD_CREATE_DETACHED attribute was set oncreationHow to make a thread detachedvoid *processfd(void *arg);int error;int fdpthread_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));}How a thread can detach itselfvoid *detachfun(void *arg)


View Full Document

U of I CS 498 - Pthreads

Documents in this Course
Lecture 5

Lecture 5

13 pages

LECTURE

LECTURE

39 pages

Assurance

Assurance

44 pages

LECTURE

LECTURE

36 pages

Load more
Download Pthreads
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Pthreads and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Pthreads 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?