Lesson One – Creating a thread

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Pthreads & Concurrency. Acknowledgements  The material in this tutorial is based in part on: POSIX Threads Programming, by Blaise Barney.
User-Level Memory Management in Linux Programming
Kernighan/Ritchie: Kelley/Pohl:
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Threads By Dr. Yingwu Zhu. Review Multithreading Models Many-to-one One-to-one Many-to-many.
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Fork Fork is used to create a child process. Most network servers under Unix are written this way Concurrent server: parent accepts the connection, forks.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
Unix Threads operating systems. User Thread Packages pthread package mach c-threads Sun Solaris3 UI threads Kernel Threads Windows NT, XP operating systems.
Pointers Applications
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.
10/16/ Realizing Concurrency using the thread model B. Ramamurthy.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Threads and Thread Control Thread Concepts Pthread Creation and Termination Pthread synchronization Threads and Signals.
CS345 Operating Systems Threads Assignment 3. Process vs. Thread process: an address space with 1 or more threads executing within that address space,
Includes slides from course CS194 at UC Berkeley, by prof. Katherine Yelick Shared Memory Programming Pthreads: an overview Ing. Andrea Marongiu
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
12/22/ Thread Model for Realizing Concurrency B. Ramamurthy.
1 Homework / Exam Finishing K&R Chapter 5 today –Skipping sections for now –Not covering section 5.12 Starting K&R Chapter 6 next Continue HW5.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
B. RAMAMURTHY 5/10/2013 Amrita-UB-MSES Realizing Concurrency using the thread model.
7/9/ Realizing Concurrency using Posix Threads (pthreads) B. Ramamurthy.
Tutorial 4. In this tutorial session we’ll see Threads.
A thread is a basic unit of CPU utilization within a process Each thread has its own – thread ID – program counter – register set – stack It shares the.
Realizing Concurrency using the thread model
CSE 220 – C Programming malloc, calloc, realloc.
Memory Management.
Constructors and Destructors
Memory allocation & parameter passing
Pointers and Dynamic Arrays
Pointers and Dynamic Arrays
Stack and Heap Memory Stack resident variables include:
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Realizing Concurrency using the thread model
Threads in C Caryl Rahn.
Threads Threads.
Boost String API & Threads
Copyright ©: Nahrstedt, Angrave, Abdelzaher
Principles of Operating Systems Lecture 8
Checking Memory Management
CSCI206 - Computer Organization & Programming
This pointer, Dynamic memory allocation, Constructors and Destructor
Dynamic Memory Allocation
Realizing Concurrency using Posix Threads (pthreads)
Realizing Concurrency using the thread model
Dynamic Memory Allocation
Memory Allocation CS 217.
Realizing Concurrency using the thread model
Constructors and Destructors
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
Pthread Prof. Ikjun Yeom TA – Mugyo
EENG212 – Algorithms & Data Structures Fall 07/08 – Lecture Notes # 5b
Realizing Concurrency using the thread model
Realizing Concurrency using Posix Threads (pthreads)
Realizing Concurrency using the thread model
Realizing Concurrency using Posix Threads (pthreads)
Dynamic Memory.
Java Programming Language
Tutorial 4.
Pointers, Dynamic Data, and Reference Types
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Lesson One – Creating a thread Thread by Example Lesson One – Creating a thread The function to be executed by the thread should take a void * parameter and return a void * exit status code . 1

Thread by Example } void ∗ thread_function ( void ∗ arg ) { // Cast the parameter into what is needed . int∗ incoming = ( int∗ ) arg ; // Do whatever is necessary using * incoming as the argument . // The thread terminates when this function returns . return NULL; } 2

pthread_ create( ) function The first parameter in pthread_create() function gives back a thread identifier that can be used in other calls. The second parameter is a pointer to a thread attribute object that you can use to set the thread’s attributes. The null pointer means to use default attributes. The third parameter is a pointer to the function the thread is to execute. The final parameter is the argument to the function. By using void pointers here, any sort of data could potentially be sent to the thread function provided proper casts are applied. In the next example I show how a single integer can be used as a thread argument. 3

pthread_join () You should plan to collect the exit status of all the threads you create by calling pthread_join( ) on each thread. Alternatively you can create a detached thread. The exit status for such threads are thrown away. The problem with detached threads is that you are never sure when they complete. Usually you want to make sure all your threads have terminated cleanly before you end the process by returning from main( ) 4

// Put something meaningful into value . value = 42; int main ( void ) { pthread_t thread ID ; void ∗ exitstatus ; int value ; // Put something meaningful into value . value = 42; // Create the thread , passing & value for the argument . pthread_create(&threadID , NULL, threadfunction , &value) ; // The main program continues while the thread executes . // Wait for the thread to terminate . pthread_join( threadID , &exitstatus ) ; // Only the main thread is running now . return 0 ; } 5

pthread_cancel ( ) If you want to kill a thread before its thread function returns normally, you can use pthread_cancel(). However, there are difficulties involved in doing that. You must be sure the thread has released any local resources that it has obtained before it actually dies. For example if a thread has dynamcially allocated memory and you cancel it before it can free that memory, your program will have a memory leak. This is different than when you kill an entire process. The operating system will typically clean up (certain) resources that are left dangling by the process. In particular, the entire address space of a process is recovered. However, the operating system will not do that for a thread since all the threads in a process share resources. 6

Lesson 2 Return result from thread Note that the thread functions are declared to return a pointer to void. However, there are some pitfalls involved in using that pointer appropriately. The code below shows one attempt at returning an integer status code from a thread function. 7

void ∗ t h r e a d_f u n c t i o n ( void ∗ ) { int code = SOME VALUE; // Set the value of ’ code ’ as appropriate . return ( void ∗ ) code ; } 8

Explanation This method will only work on machines where integers can be converted to a pointer and then back to an integer without loss of information. On some machines such conversions are dangerous. In fact this method will fail in all cases where one attempts to return an object, such as a structure, that is larger than a pointer. 9

2nd Attempt void ∗ t h r e a d_f u n c t i o n ( void ∗ ) { char b u f f e r [ 6 4 ] ; // Fill up the buffer with something good . return b u f f e r ; } The code above returns a pointer to an internal buffer where the return value is stored. While the example shows an array of characters for the buffer, one can easily imagine it being an array of any necessary type, or a single object such as an integer status code or a structure with many members. 10

...fail again Alas, the code above fails because the internal buffer is automatic and it vanishes as soon as the thread function returns. The pointer given back to the calling thread points at undefined memory. This is another example of the classic dangling pointer error. 11

3rd attempt void ∗ threadfunction ( void ∗ ) { static char buffer[ 6 4 ] ; // Fill up the buffer with something good . return buffer ; } 12

...fail again This method might be satisfactory in some cases, but it doesn’t work in the common case of multiple threads running the same thread function. In such a situation the second thread will overwrite the static buffer with its own data and destroy that left by the first thread. Global data suffers from this same problem since global data always has static duration. 13

Final attempt void∗ t h r e a d_f u n c t i o n ( void ∗ ) { char ∗ b u f f e r = ( char ∗ ) m a l l o c ( 6 4 ) ; // Fill up the buffer with something good . return b u f f e r ; } This version allocates buffer space dynamically. This approach will work cor- rectly even if multiple threads execute the thread function. Each will allocate a different array and store the address of that array in a stack variable. Every thread has its own stack so automatic data objects are different for each thread. 14

Lesson 3: Receiving Return value of a thread In order to receive the return value of a thread the higher level thread must join with the subordinate thread. As below void ∗ exitstatus; // Wait for the thread to terminate . pthread_join ( threadID , &exitstatus ) ; 15

threadresult = ( char ∗ ) exitstatus ; The pthread join() function blocks until the thread specified by its first argument terminates. It then stores into the pointer pointed at by its second argument the value returned by the thread function. To use this pointer, the higher level thread must cast it into an appropriate type and dereference it. For example: char ∗ threadresult ; threadresult = ( char ∗ ) exitstatus ; printf ( "I got %s back from the thread .\ n" , threadresult ) ; free ( exitstatus ); 16

The thread function allocated the space for the return value dynamically then It is essential for the higher level thread to free that space when it no longer needs the return value. If this isn’t done the program will leak memory 17

malloc() The malloc() function dynamically allocates memory when required. This function allocates ‘size’ byte of memory and returns a pointer to the first byte or NULL if there is some kind of error.span> Format is as follows. void * malloc (size_t size);