In the example, since printf() was never declared, the compiler had to try to figure out what kind of function it is.
|
|
- Darcy Snow
- 5 years ago
- Views:
Transcription
1 Ans 1.a Dynamic lookup means that when a message is sent to an object, the method to be executed is selected dynamically, at run time, according to the implementation of the object that receives the message. In other words, the object chooses how to respond to a message. b. Dynamic method lookup is the process of determining which method definition a method signature denotes during runtime, based on the type of the object. 2. Delegation : Delegation allows the behavior of an object to be defined in terms of the behavior of another object. ie, Delegation is alternative to class inheritance. Delegation is a way of making object composition as powerful as inheritance. In delegation, two objects are involved in handling a request: a receiving object delegates operations to its delegate. this is analogous to the child classes sending requests to the parent classes. 3.Implicit and Explicit functions : An implicit function is one where the compiler assumes that the function is declared & defined elsewhere. That is, the compiler doesn't know anything more about the function than what it can figure out when you call it. int main() printf( "Hello world!\n" ); /* printf()!!?? what's that? */ return 0; In the example, since printf() was never declared, the compiler had to try to figure out what kind of function it is. It looks like void printf( const char* ); We know different, but that is close enough so it works. (Usually. A C program is automatically linked with the actual printf() function.) Now, if we want to fix the above, we can declare the function properly -- that is, explicitly: int printf( const char*,... ); /* here the function is explicitly declared */ int main() printf( "Hello world!\n" ); /* now it can be used, since the compiler knows about it */
2 return 0; However the function must still be defined somewhere. In the case of printf() it is defined in the standard library that is automatically linked with your C program. For functions you create yourself you must also declare them: void print_sum( int a, int b ); /* explicit declaration */ int main() print_sum( 27, 15 ); /* happy compiler */ return 0; void print_sum( int a, int b ) /* definition */ printf( "%d + %d = %d\n", a, b, a + b ); /* implicit function use */ Ans. Different formatting activities supported by Stream Manipulators are : 1. Setting field width. 2. Precision. 3. Unsetting format flags. 4. Flushing stream. 5. Inserting newline in the output stream and flushing the stream. 6. Inserting the null character in the output stream. 7. Skipping whitespace. 8. Setting the fill character in field. /* * File: main.cpp */ #include <iostream> #include <iomanip> using namespace std; int main() float basic, ta,da,gs; basic=10000; ta=800; da=5000; gs=basic+ta+da; cout<<"c++ "<<endl; // Inserting newline in the output stream //Set width and set fill
3 cout << setw(20) << setfill('*') << "SNJB" << setw(20) << setfill('*')<<"program"<< endl; cout.setf(ios::right); //Format flags cout<<setw(10)<<setprecision(3) <<"Basic"<<setw(10)<<basic<<endl <<setw(10)<<"ta"<<setw(10)<<ta<<endl <<setw(10)<<"da"<<setw(10)<<da<<endl <<setw(10)<<"gs"<<setw(10)<<gs<<endl; cout<<flush; //Flushing stream. return 0; OR Ans. Abstraction is the act of representing essential features without including the background details or explanations. In the computer science and software engineering domain, the abstraction principle is used to reduce complexity and allow efficient design and implementation of complex software systems. It is important due to following reasons : Class data are protected from inadvertent user-level errors, which might corrupt the state of the object. The class implementation can change without requiring the change in user-level code. Abstract Base Class : A pure virtual function is a function which does not have definition of its own. The classes which derive from this class need to provide definition for such function. A class containing at least one such pure virtual function is called as abstract base class. We cannot create objects of abstract class because it contains functions which have no definition. We can create pointers and references to an abstract class. Consider example of base class Base and derived class Derives. - The function show() is made pure virtual in the base class Base. It is overridden by the derived class. So the class Base becomes abstract base class. class Base //Abstract base class public: virtual void show() = 0; //Pure Virtual Function ; class Derived:public Base public: void show() cout << "Implementation of Virtual Function in Derived class"; ;
4 int main() Base obj; Base *b; Derived d; b = &d; b->show(); //Compile Time Error since an object of Base class which is abstract cannot be created Ans b) Type conversion is a way of, implicitly or explicitly, changing an entity of one data type into another. Implicit type conversion : known as coercion, is an automatic type conversion by the compiler. Explicit type conversion : Explicitly defined within a program (instead of being done by a compiler for implicit type conversion). Example : double d; long l; int i; double da = 3.3; if (d > i) d = i; //implicit type conversion if (i > l) l = i; if (d = = l) d *= 2; int result = (int)da; //explicit type conversion Although d, l and i belong to different data types, they will be automatically converted to equal data types each time a comparison or assignment is executed. Ans 3 a) A process control block or PCB is a data structure (a table) that holds information about a process. Every process or program that runs needs a PCB. When a user requests to run a particular program, the operating system constructs a process control block for that program. Typical information that is stored in a process control block is : The current state of the process i.e., whether it is ready, running, waiting, or whatever.
5 Unique identification of the process in order to track "which is which" information. A pointer to parent process. Similarly, a pointer to child process (if it exists). The priority of process (a part of CPU scheduling information). Pointers to locate memory of processes. A register save area. The processor it is running on. Ans b)the challenges for multicore software development are: 1) Software Decomposition : a. Choosing right way of decomposition to represent a problem or solution. b. Whether the decomposition is complete, accurate and appropriate c. Selecting appropriate model of problem and solution. 2) Task-to-Task Communication : a. Create IPC correctly b. Have proper User and File Permissions c. Properly release the resources to avoid lockups and resource leaks d. Mentioning proper data type and size 3) Concurrent Access to Data or Resources by Multiple Tasks or Agents : Manage synchronization of tasks 4) Identifying the Relationships between Concurrently Executing Tasks 5) Controlling Resource Contention Between Tasks 6) Determining Number of processes or threads needed : May be based on Application Speed, Optimality 7) Finding Reliable and Reproducible Debugging and Testing 8) Communicating a Design That Has Multiprocessing Components : Use proper representation e.g Unified Modeling Language Diagrams.
6 9) Implementing Multiprocessing and Multithreading in C++ : Use proper concurrency supporting libraries. Ans c) Overloading a function template means having different sets of function templates which differ in their parameter list. Consider following example : #include <iostream> template <class X> void func(x a) // Function code; cout << Inside f(x a) \n ; template <class X, class Y> void func(x a, Y b) //overloading function template func() // Function code; cout << Inside f(x a, Y b) \n ; int main() func(10); // calls func(x a) func(10, 20); // calls func(x a, Y b) return 0; Ans. Data Race : A data race occurs when: two or more threads concurrently accessing a location of memory one of them is a write one of them is unsynchronized // Execute this function on five threads simultaneously for ( int i = 0; i < 10000; i++ )
7 x = x + 1; Use of a synchronisation object across all the threads involved (e.g. a mutex) would address the issue. DeadLock : a) Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called deadlock. b) Deadlock occurs when threads are unable to execute because they need more shared resources, and they are still holding shared resources while they wait. If two or more of these threads are both doing this, they might each want 75% of system memory to do something, but each one can only get 50%. Because they're waiting for more memory to be available, they are deadlocked. Neither one will ever make any progress unless one is killed. The synchronization mechanisms can be used to prevent deadlocks between multiple tasks by implementing the synchronization access policies as listed below and managing critical sections of tasks. 1) Semaphore and mutexes 2) Read-write locks 3) Condition variables #include <pthread.h> #include <stdio.h> #include "check.h" /* This example shows the corruption that can result if no serialization is done and also shows the use of pthread_mutex_lock(). Call it with no parameters to use pthread_mutex_lock() to protect the critical section, or 1 or more parameters to show data corruption that occurs without locking. */ #define LOOPCONSTANT #define THREADS 10 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int i,j,k,l; int uselock=1; void *threadfunc(void *parm) int loop = 0; int rc; for (loop=0; loop<loopconstant; ++loop) if (uselock) rc = pthread_mutex_lock(&mutex); checkresults("pthread_mutex_lock()\n", rc); ++i; ++j; ++k; ++l; if (uselock) rc = pthread_mutex_unlock(&mutex); checkresults("pthread_mutex_unlock()\n", rc); return NULL;
8 int main(int argc, char **argv) pthread_t threadid[threads]; int rc=0; int loop=0; pthread_attr_t pta; printf("entering testcase\n"); printf("give any number of parameters to show data corruption\n"); if (argc!= 1) printf("a parameter was specified, no serialization is being done!\n"); uselock = 0; pthread_attr_init(&pta); pthread_attr_setdetachstate(&pta, PTHREAD_CREATE_JOINABLE); printf("creating %d threads\n", THREADS); for (loop=0; loop<threads; ++loop) rc = pthread_create(&threadid[loop], &pta, threadfunc, NULL); checkresults("pthread_create()\n", rc); printf("wait for results\n"); for (loop=0; loop<threads; ++loop) rc = pthread_join(threadid[loop], NULL); checkresults("pthread_join()\n", rc); printf("cleanup and show results\n"); pthread_attr_destroy(&pta); pthread_mutex_destroy(&mutex); printf("\nusing %d threads and LOOPCONSTANT = %d\n", THREADS, LOOPCONSTANT); printf("values are: (should be %d)\n", THREADS * LOOPCONSTANT); printf(" ==>%d, %d, %d, %d\n", i, j, k, l); printf("main completed\n"); return 0; Output : Entering testcase Give any number of parameters to show data corruption Creating 10 threads Wait for results Cleanup and show results Using 10 threads and LOOPCONSTANT = Values are: (should be ) ==> , , , Main completed Output (data corruption without locking example) Entering testcase Give any number of parameters to show data corruption A parameter was specified, no serialization is being done! Creating 10 threads Wait for results Cleanup and show results
9 Using 10 threads and LOOPCONSTANT = Values are: (should be ) ==>883380, , , Main completed Ans. An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built upon three keywords: try, catch, and throw. throw: A program throws an exception when a problem shows up. This is done using a throw keyword. catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception. try: A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks. #include <iostream> using namespace std; double division(int a, int b) if( b == 0 ) throw "Division by zero condition!"; return (a/b); int main () int x = 50; int y = 0; double z = 0; try z = division(x, y); cout << z << endl; catch (const char* msg) cerr << msg << endl; return 0;
10 Ans. POSIX thread library defines a thread attribute object that defines behavior of a thread or group of thread and encapsulates a subset of the properties of the thread. These attributes are accessible and modifiable by the creator of the thread as listed below: Contention Scope.. Process Scope and System Scope Stack Size Stack Address Detached State Priority Scheduling Policy and parameters 1) Initialization : The function pthread_attr_init() is used to initialize object attributes to their default values. The function is prototyped by: int pthread_attr_init(pthread_attr_t *tattr); 2) Destroying Thread Attributes : The function pthread_attr_destroy() is used to remove the storage allocated during initialization. The attribute object becomes invalid. It is prototyped by : int pthread_attr_destroy(pthread_attr_t *tattr); 3) Thread's Detach State : When a thread is created detached (PTHREAD_CREATE_DETACHED), its thread ID and other resources can be reused as soon as the thread terminates. If you do not want the calling thread to wait for the thread to terminate then call the function pthread_attr_setdetachstate(). When a thread is created nondetached (PTHREAD_CREATE_JOINABLE), it is assumed that you will be waiting for it. That is, it is assumed that you will be executing a pthread_join() on the thread. Whether a thread is created detached or nondetached, the process does not exit until all threads have exited. pthread_attr_setdetachstate() is prototyped by: int pthread_attr_setdetachstate(pthread_attr_t *tattr,int detachstate); pthread_attr_setdetachstate() returns zero after completing successfully. Any other returned value indicates that an error occurred. If the following condition occurs, the function fails and returns the corresponding value. 4) Thread's Set Scope : A thread may be bound (PTHREAD_SCOPE_SYSTEM) or an unbound (PTHREAD_SCOPE_PROCESS). Both these types of types are accessible only within a given process. The function pthread_attr_setscope() to create a bound or unbound thread. It is prototyped by: int pthread_attr_setscope(pthread_attr_t *tattr,int scope); Scope takes on the value of either PTHREAD_SCOP_SYSTEM or PTHREAD_SCOPE_PROCESS. pthread_attr_setscope() returns zero after completing successfully. Any other returned value indicates that an error occurred and an appropriate value is returned. 5) Thread Scheduling Policy : The POSIX draft standard specifies scheduling policy attributes of SCHED_FIFO (first-infirst-out), SCHED_RR (round-robin), or SCHED_OTHER (an implementation-defined method). SCHED_FIFO and SCHED_RR are optional in POSIX, and only are supported for real time bound threads. Currently, only the Solaris
11 SCHED_OTHER default value is supported in pthreads.. The function is used to set the scheduling policy.it is prototyped by: int pthread_attr_setschedpolicy(pthread_attr_t *tattr, int policy); pthread_attr_setschedpolicy() returns zero after completing successfully. Any other returned value indicates that an error occurred. 6) Thread Inherited Scheduling Policy : The function pthread_attr_setinheritsched() can be used to the inherited scheduling policy of a thread. It is prototyped by: int pthread_attr_setinheritsched(pthread_attr_t *tattr, int inherit); An inherit value of PTHREAD_INHERIT_SCHED (the default) means that the scheduling policies defined in the creating thread are to be used, and any scheduling attributes defined in the pthread_create() call are to be ignored. If PTHREAD_EXPLICIT_SCHED is used, the attributes from the pthread_create() call are to be used. The function returns zero after completing successfully. Any other returned value indicates that an error occurred. 7) Set Scheduling Parameters : Scheduling parameters are defined in the sched_param structure; only priority sched_param.sched_priority is supported. This priority is an integer value the higher the value the higher a thread's proiority for scehduling. Newly created threads run with this priority. The pthread_attr_setschedparam() is used to set this stucture appropiately. It is prototyped by: int pthread_attr_setschedparam(pthread_attr_t *tattr, const struct sched_param *param); and returns zero after completing successfully. Any other returned value indicates that an error occurred. 8) Set Stack size : There are very few occasions when it is appropriate to specify a stack, its size, or both. It is difficult even for an expert to know if the right size was specified. This is because even a program compliant with ABI standards cannot determine its stack size statically. Its size is dependent on the needs of the particular runtime environment in which it executes. You can get the absolute minimum limit on stack size by calling the macro PTHREAD_STACK_MIN (defined in <pthread.h>), which returns the amount of stack space required for a thread that executes a NULL procedure. Useful threads need more than this, so be very careful when reducing the stack size. The function pthread_attr_setstacksize() is used to set this a thread's stack size, it is prototyped by: int pthread_attr_setstacksize(pthread_attr_t *tattr, int stacksize); The stacksize attribute defines the size of the stack (in bytes) that the system will allocate. The size should not be less than the system-defined minimum stack size. pthread_attr_setstacksize() returns zero after completing successfully. Any other returned value indicates that an error occurred. An example call to this function is: #include <pthread.h> void main() pthread_attr_t tattr; pthread_t tid; int ret; void *start_routine; void arg ; int stacksize; int newprio;
12 sched_param param; /* set the priority; others are unchanged */ newprio = 30; param.sched_priority = newprio; /* initialize an attribute to the default value */ ret = pthread_attr_init(&tattr); /* set the thread detach state */ ret = pthread_attr_setdetachstate(&tattr,pthread_create_detached); /* BOUND behavior */ ret = pthread_attr_setscope(&tattr, PTHREAD_SCOPE_SYSTEM); /* set the new scheduling param */ ret = pthread_attr_setschedparam (&tattr, ¶m); /* set the scheduling policy to SCHED_OTHER */ ret = pthread_attr_setschedpolicy(&tattr, SCHED_OTHER); /* setting a new size */ stacksize = (PTHREAD_STACK_MIN + 0x4000); ret = pthread_attr_setstacksize(&tattr, stacksize); /* setting the base address in the attribute */ ret = pthread_attr_setstackaddr(&tattr, stackbase); /*create thread with the atrribute ret = pthread_create(&tid, &tattr, start_routine, arg); pthread_exit(); Ans. Each process contain one or more threads. These are task executed and managed by operating system and are called as Software Threads. On the other hand there are processor. Nowadays it contains few cores. If processors have, for example 4 cores( physical cores ), it can process even more operations than 4 at a time, because of some magic implementations in each of the core ( like in Hyper-threading technology ). So even if processor have 4 physical cores operating system see that it has more logical cores known as Hardware Threads. Operating system recognizes how many hardware threads processor have and according to that number schedules software threads to each of them. Both of these threads if more increase the efficiency of the core. OR Ans. 1. The operating system continuously selects a single thread to run from a system wide collection of all threads that are not waiting for the completion of an I/O request or are not blocked by some other activity 2. The Pthreads standard defines a thread-scheduling interface that allows programs with real-time tasks to get involved in the process.
13 Using the Pthreads scheduling feature, you can designate how threads share the available processing power. You may decide that all threads should have equal access to all available CPUs, or you can give some threads preferential treatment. In some applications, it's beneficial to give those threads that perform important tasks an advantage over those that perform background work. For instance, in a process-control application, a thread that responds to input for special devices could be given priority over a thread that simply maintains the log. 3. The eligibility of any given thread for special scheduling treatment is determined by the settings of two threadspecific attributes: Scheduling priority A thread's scheduling priority, in relation to that of other threads, determines which thread gets preferential access to the available CPUs at any given time. Scheduling policy A thread's scheduling policy is a way of expressing how threads of the same priority run and share the available CPUs. Scheduling Priority The scheduler begins by looking at an array of priority queues, as shown in Figure 4-8. There is a queue for each scheduling priority and, at any given priority level, the threads that are assigned that priority reside. When looking for a thread to run in a processing slot, the scheduler starts with the highest priority queue and works its way down to the lower priority queues until it finds the first thread. In this illustration only three of the priority queues hold runnable threads. When running threads either involuntarily give up their processing slot(more on this later) or go from blocked to runnable, they are placed at the end of the queue for their priority. Over time, the population of the priority queues will grow and decline. Whenever a thread with a higher priority than the current running thread becomes runnable, it interrupts the running thread and replaces it in the processing slot. From the standpoint of the thread that's been replaced, this is known as an involuntary context switch. Scheduling Policy A thread's scheduling policy determines how long it runs when it moves from the head of its priority queue to a processing slot. The two main scheduling policies are SCHED_FIFO and SCHED-RR: SCHED_FIFO
14 This policy (first-in first-out) lets a thread run until it either exits or blocks. As soon as it becomes unblocked, a blocked thread that has given up its processing slot is placed at the end of its priority queue. SCHED_RR This policy (round robin) allows a thread to run for only a fixed amount of time before it must yield its processing slot to another thread of the same priority. This fixed amount of time is usually referred to as a quantum. When a thread is interrupted, it is placed at the end of its priority queue. The Pthreads standard defines an additional policy, SCHED_OTHER, and leaves its behavior up to the implementors. On most systems, selecting SCHED_OTHER will give a thread a policy that uses some sort of time sharing with priority adjustment. By default, all threads start life with the SCHED_OTHER policy. Ans. The context of a process includes : The context of a thread includes : Context Switching of thread exists due to preemption of a thread If the threads belong to same process, they share the same address space because the threads are contained in the address of the process to which they belong. Some information is however local or unique to the thread, while other are contained within various segments of the process. INFORMATION UNIQUE TO A THREAD 1. THREAD ID.assigned when thread is created 2. State and Priority 3. Processor registers 4. Stack
Pthread (9A) Pthread
Pthread (9A) Pthread Copyright (c) 2012 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later
More informationpthreads Announcement Reminder: SMP1 due today Reminder: Please keep up with the reading assignments (see class webpage)
pthreads 1 Announcement Reminder: SMP1 due today Reminder: Please keep up with the reading assignments (see class webpage) 2 1 Thread Packages Kernel thread packages Implemented and supported at kernel
More informationpthreads CS449 Fall 2017
pthreads CS449 Fall 2017 POSIX Portable Operating System Interface Standard interface between OS and program UNIX-derived OSes mostly follow POSIX Linux, macos, Android, etc. Windows requires separate
More informationCPSC 313: Intro to Computer Systems. POSIX Threads. Latency Hiding / Multiprogramming (covered earlier) Ease of Programming (covered now)
Why Threads? Latency Hiding / Multiprogramming (covered earlier) Ease of Programming (covered now) (R&R, Chapter 12) Thread Management Thread Safety Thread Attributes Why Threads? Latency Hiding / Multiprogramming
More informationThreads. Threads (continued)
Threads A thread is an alternative model of program execution A process creates a thread through a system call Thread operates within process context Use of threads effectively splits the process state
More informationreal time operating systems course
real time operating systems course 4 introduction to POSIX pthread programming introduction thread creation, join, end thread scheduling thread cancellation semaphores thread mutexes and condition variables
More informationPOSIX threads CS 241. February 17, Copyright University of Illinois CS 241 Staff
POSIX threads CS 241 February 17, 2012 Copyright University of Illinois CS 241 Staff 1 Recall: Why threads over processes? Creating a new process can be expensive Time A call into the operating system
More informationLecture 19: Shared Memory & Synchronization
Lecture 19: Shared Memory & Synchronization COMP 524 Programming Language Concepts Stephen Olivier April 16, 2009 Based on notes by A. Block, N. Fisher, F. Hernandez-Campos, and D. Stotts Forking int pid;
More informationThreads. studykorner.org
Threads Thread Subpart of a process Basic unit of CPU utilization Smallest set of programmed instructions, can be managed independently by OS No independent existence (process dependent) Light Weight Process
More informationCSCE 313 Introduction to Computer Systems. Instructor: Dr. Dezhen Song
CSCE 313 Introduction to Computer Systems Instructor: Dr. Dezhen Song POSIX Threads Why Threads? Latency Hiding / Multiprogramming (covered earlier) Ease of Programming (covered now) POSIX Threads (R&R,
More informationCSCE 313: Intro to Computer Systems
CSCE 313 Introduction to Computer Systems Instructor: Dr. Guofei Gu http://courses.cse.tamu.edu/guofei/csce313/ Why Threads? Latency Hiding / Multiprogramming (covered earlier) Ease of Programming (covered
More informationPOSIX Threads. HUJI Spring 2011
POSIX Threads HUJI Spring 2011 Why Threads The primary motivation for using threads is to realize potential program performance gains and structuring. Overlapping CPU work with I/O. Priority/real-time
More informationMultithreaded Programming
Multithreaded Programming The slides do not contain all the information and cannot be treated as a study material for Operating System. Please refer the text book for exams. September 4, 2014 Topics Overview
More informationPreview. What are Pthreads? The Thread ID. The Thread ID. The thread Creation. The thread Creation 10/25/2017
Preview What are Pthreads? What is Pthreads The Thread ID The Thread Creation The thread Termination The pthread_join() function Mutex The pthread_cancel function The pthread_cleanup_push() function The
More informationHigh Performance Computing Course Notes Shared Memory Parallel Programming
High Performance Computing Course Notes 2009-2010 2010 Shared Memory Parallel Programming Techniques Multiprocessing User space multithreading Operating system-supported (or kernel) multithreading Distributed
More informationThread. Disclaimer: some slides are adopted from the book authors slides with permission 1
Thread Disclaimer: some slides are adopted from the book authors slides with permission 1 IPC Shared memory Recap share a memory region between processes read or write to the shared memory region fast
More informationCPU Scheduling (Part II)
CPU Scheduling (Part II) Amir H. Payberah amir@sics.se Amirkabir University of Technology (Tehran Polytechnic) Amir H. Payberah (Tehran Polytechnic) CPU Scheduling 1393/7/28 1 / 58 Motivation Amir H. Payberah
More informationChapter 4 Concurrent Programming
Chapter 4 Concurrent Programming 4.1. Introduction to Parallel Computing In the early days, most computers have only one processing element, known as the Central Processing Unit (CPU). Due to this hardware
More informationThreads. What is a thread? Motivation. Single and Multithreaded Processes. Benefits
CS307 What is a thread? Threads A thread is a basic unit of CPU utilization contains a thread ID, a program counter, a register set, and a stack shares with other threads belonging to the same process
More informationCSE 333 SECTION 9. Threads
CSE 333 SECTION 9 Threads HW4 How s HW4 going? Any Questions? Threads Sequential execution of a program. Contained within a process. Multiple threads can exist within the same process. Every process starts
More informationMultithreading Programming II
Multithreading Programming II Content Review Multithreading programming Race conditions Semaphores Thread safety Deadlock Review: Resource Sharing Access to shared resources need to be controlled to ensure
More informationCS333 Intro to Operating Systems. Jonathan Walpole
CS333 Intro to Operating Systems Jonathan Walpole Threads & Concurrency 2 Threads Processes have the following components: - an address space - a collection of operating system state - a CPU context or
More informationDefinition Multithreading Models Threading Issues Pthreads (Unix)
Chapter 4: Threads Definition Multithreading Models Threading Issues Pthreads (Unix) Solaris 2 Threads Windows 2000 Threads Linux Threads Java Threads 1 Thread A Unix process (heavy-weight process HWP)
More informationCS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University
CS 333 Introduction to Operating Systems Class 3 Threads & Concurrency Jonathan Walpole Computer Science Portland State University 1 Process creation in UNIX All processes have a unique process id getpid(),
More informationCS510 Operating System Foundations. Jonathan Walpole
CS510 Operating System Foundations Jonathan Walpole Threads & Concurrency 2 Why Use Threads? Utilize multiple CPU s concurrently Low cost communication via shared memory Overlap computation and blocking
More informationCS510 Operating System Foundations. Jonathan Walpole
CS510 Operating System Foundations Jonathan Walpole The Process Concept 2 The Process Concept Process a program in execution Program - description of how to perform an activity instructions and static
More informationPosix Threads (Pthreads)
Posix Threads (Pthreads) Reference: Programming with POSIX Threads by David R. Butenhof, Addison Wesley, 1997 Threads: Introduction main: startthread( funk1 ) startthread( funk1 ) startthread( funk2 )
More informationCS 3305 Intro to Threads. Lecture 6
CS 3305 Intro to Threads Lecture 6 Introduction Multiple applications run concurrently! This means that there are multiple processes running on a computer Introduction Applications often need to perform
More informationCS-345 Operating Systems. Tutorial 2: Grocer-Client Threads, Shared Memory, Synchronization
CS-345 Operating Systems Tutorial 2: Grocer-Client Threads, Shared Memory, Synchronization Threads A thread is a lightweight process A thread exists within a process and uses the process resources. It
More informationCS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University
CS 333 Introduction to Operating Systems Class 3 Threads & Concurrency Jonathan Walpole Computer Science Portland State University 1 The Process Concept 2 The Process Concept Process a program in execution
More informationUnix. Threads & Concurrency. Erick Fredj Computer Science The Jerusalem College of Technology
Unix Threads & Concurrency Erick Fredj Computer Science The Jerusalem College of Technology 1 Threads Processes have the following components: an address space a collection of operating system state a
More informationCSCI4430 Data Communication and Computer Networks. Pthread Programming. ZHANG, Mi Jan. 26, 2017
CSCI4430 Data Communication and Computer Networks Pthread Programming ZHANG, Mi Jan. 26, 2017 Outline Introduction What is Multi-thread Programming Why to use Multi-thread Programming Basic Pthread Programming
More informationChapter 6: CPU Scheduling
Chapter 6: CPU Scheduling Silberschatz, Galvin and Gagne Histogram of CPU-burst Times 6.2 Silberschatz, Galvin and Gagne Alternating Sequence of CPU And I/O Bursts 6.3 Silberschatz, Galvin and Gagne CPU
More informationOperating systems and concurrency (B10)
Operating systems and concurrency (B10) David Kendall Northumbria University David Kendall (Northumbria University) Operating systems and concurrency (B10) 1 / 26 Introduction This lecture looks at Some
More informationMulticore and Multiprocessor Systems: Part I
Chapter 3 Multicore and Multiprocessor Systems: Part I Max Planck Institute Magdeburg Jens Saak, Scientific Computing II 44/337 Symmetric Multiprocessing Definition (Symmetric Multiprocessing (SMP)) The
More informationCSci 4061 Introduction to Operating Systems. (Threads-POSIX)
CSci 4061 Introduction to Operating Systems (Threads-POSIX) How do I program them? General Thread Operations Create/Fork Allocate memory for stack, perform bookkeeping Parent thread creates child threads
More informationHPCSE - I. «Introduction to multithreading» Panos Hadjidoukas
HPCSE - I «Introduction to multithreading» Panos Hadjidoukas 1 Processes and Threads POSIX Threads API Outline Thread management Synchronization with mutexes Deadlock and thread safety 2 Terminology -
More informationUser Space Multithreading. Computer Science, University of Warwick
User Space Multithreading 1 Threads Thread short for thread of execution/control B efore create Global During create Global Data Data Executing Code Code Stack Stack Stack A fter create Global Data Executing
More informationOperating system concepts. Task scheduling
Operating system concepts Task scheduling Task scheduling (thread scheduling) Target of scheduling are ready tasks ACTIVE TASK BLOCKED TASKS PASSIVE TASKS READY TASKS Active task currently running on processor
More informationAgenda. Process vs Thread. ! POSIX Threads Programming. Picture source:
Agenda POSIX Threads Programming 1 Process vs Thread process thread Picture source: https://computing.llnl.gov/tutorials/pthreads/ 2 Shared Memory Model Picture source: https://computing.llnl.gov/tutorials/pthreads/
More informationRicardo Rocha. Department of Computer Science Faculty of Sciences University of Porto
Ricardo Rocha Department of Computer Science Faculty of Sciences University of Porto For more information please consult Advanced Programming in the UNIX Environment, 3rd Edition, W. Richard Stevens and
More informationLSN 13 Linux Concurrency Mechanisms
LSN 13 Linux Concurrency Mechanisms ECT362 Operating Systems Department of Engineering Technology LSN 13 Creating Processes fork() system call Returns PID of the child process created The new process is
More informationThreaded Programming. Lecture 9: Alternatives to OpenMP
Threaded Programming Lecture 9: Alternatives to OpenMP What s wrong with OpenMP? OpenMP is designed for programs where you want a fixed number of threads, and you always want the threads to be consuming
More informationANSI/IEEE POSIX Standard Thread management
Pthread Prof. Jinkyu Jeong( jinkyu@skku.edu) TA Jinhong Kim( jinhong.kim@csl.skku.edu) TA Seokha Shin(seokha.shin@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu The
More informationPOSIX PTHREADS PROGRAMMING
POSIX PTHREADS PROGRAMMING Download the exercise code at http://www-micrel.deis.unibo.it/~capotondi/pthreads.zip Alessandro Capotondi alessandro.capotondi(@)unibo.it Hardware Software Design of Embedded
More informationCSE 333 Section 9 - pthreads
CSE 333 Section 9 - pthreads Welcome back to section! We re glad that you re here :) Process A process has a virtual address space. Each process is started with a single thread, but can create additional
More informationXenomai Real-Time nanokernel
Xenomai Real-Time nanokernel Ricardo Correia Pinto ricardo.pinto@ciencias.ulisboa.pt Faculty of Sciences - University of Lisboa Sistemas Embebidos e de Tempo-Real 2014/2015 Xenomai Real-Time nanokernel
More informationQ1: /8 Q2: /30 Q3: /30 Q4: /32. Total: /100
ECE 2035(A) Programming for Hardware/Software Systems Fall 2013 Exam Three November 20 th 2013 Name: Q1: /8 Q2: /30 Q3: /30 Q4: /32 Total: /100 1/10 For functional call related questions, let s assume
More informationThreads. Today. Next time. Why threads? Thread model & implementation. CPU Scheduling
Threads Today Why threads? Thread model & implementation Next time CPU Scheduling What s in a process A process consists of (at least): An address space Code and data for the running program Thread state
More informationIntroduction to pthreads
CS 220: Introduction to Parallel Computing Introduction to pthreads Lecture 25 Threads In computing, a thread is the smallest schedulable unit of execution Your operating system has a scheduler that decides
More informationCSE 306/506 Operating Systems Threads. YoungMin Kwon
CSE 306/506 Operating Systems Threads YoungMin Kwon Processes and Threads Two characteristics of a process Resource ownership Virtual address space (program, data, stack, PCB ) Main memory, I/O devices,
More informationOutline. CS4254 Computer Network Architecture and Programming. Introduction 2/4. Introduction 1/4. Dr. Ayman A. Abdel-Hamid.
Threads Dr. Ayman Abdel-Hamid, CS4254 Spring 2006 1 CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid Computer Science Department Virginia Tech Threads Outline Threads (Chapter
More informationLecture 4 Threads. (chapter 4)
Bilkent University Department of Computer Engineering CS342 Operating Systems Lecture 4 Threads (chapter 4) Dr. İbrahim Körpeoğlu http://www.cs.bilkent.edu.tr/~korpe 1 References The slides here are adapted/modified
More informationThreads. To do. Why threads? Thread model & implementation. q q q. q Next time: Synchronization
Threads To do q q q Why threads? Thread model & implementation q Next time: Synchronization What s in a process A process consists of (at least): An address space Code and data for the running program
More informationConcurrency, Thread. Dongkun Shin, SKKU
Concurrency, Thread 1 Thread Classic view a single point of execution within a program a single PC where instructions are being fetched from and executed), Multi-threaded program Has more than one point
More informationScheduling Policies. Threads Library. Lightweight Processes
Scheduling Policies User Unbound Threads Bound Threads Threads Library Kernel Lightweight Processes The threads library uses underlying threads of control called lightweight processes that are supported
More informationLecture Contents. 1. Overview. 2. Multithreading Models 3. Examples of Thread Libraries 4. Summary
Lecture 4 Threads 1 Lecture Contents 1. Overview 2. Multithreading Models 3. Examples of Thread Libraries 4. Summary 2 1. Overview Process is the unit of resource allocation and unit of protection. Thread
More informationLecture 4. Threads vs. Processes. fork() Threads. Pthreads. Threads in C. Thread Programming January 21, 2005
Threads vs. Processes Lecture 4 Thread Programming January 21, 2005 fork() is expensive (time, memory) Interprocess communication is hard. Threads are lightweight processes: one process can contain several
More information11/04/2018. Outline. Process. Process. Pthread Library. Process and threads
Outline 1. General descriptions 2. Thread management 3. Scheduler(s) in Linux 4. Time management 5. Handling periodic threads 6. Mutual exclusion 7. Examples Process A process is the main execution entity
More informationShort Notes of CS201
#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system
More informationPOSIX Threads. Paolo Burgio
POSIX Threads Paolo Burgio paolo.burgio@unimore.it The POSIX IEEE standard Specifies an operating system interface similar to most UNIX systems It extends the C language with primitives that allows the
More informationMulti-threaded Programming
Multi-threaded Programming Trifon Ruskov ruskov@tu-varna.acad.bg Technical University of Varna - Bulgaria 1 Threads A thread is defined as an independent stream of instructions that can be scheduled to
More informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
More informationCS370 Operating Systems
CS370 Operating Systems Colorado State University Yashwant K Malaiya Spring 2018 Lecture 7 Threads Slides based on Text by Silberschatz, Galvin, Gagne Various sources 1 1 FAQ How many processes can a core
More informationThread and Synchronization
Thread and Synchronization pthread Programming (Module 19) Yann-Hang Lee Arizona State University yhlee@asu.edu (480) 727-7507 Summer 2014 Real-time Systems Lab, Computer Science and Engineering, ASU Pthread
More informationThreads. Jo, Heeseung
Threads Jo, Heeseung Multi-threaded program 빠른실행 프로세스를새로생성에드는비용을절약 데이터공유 파일, Heap, Static, Code 의많은부분을공유 CPU 를보다효율적으로활용 코어가여러개일경우코어에 thread 를할당하는방식 2 Multi-threaded program Pros. Cons. 대량의데이터처리에적합 - CPU
More informationCPSC 341 OS & Networks. Threads. Dr. Yingwu Zhu
CPSC 341 OS & Networks Threads Dr. Yingwu Zhu Processes Recall that a process includes many things An address space (defining all the code and data pages) OS resources (e.g., open files) and accounting
More informationCS370 Operating Systems
CS370 Operating Systems Colorado State University Yashwant K Malaiya Fall 2017 Lecture 8 Slides based on Text by Silberschatz, Galvin, Gagne Various sources 1 1 FAQ How many partners can we cave for project:
More informationCS 326: Operating Systems. Process Execution. Lecture 5
CS 326: Operating Systems Process Execution Lecture 5 Today s Schedule Process Creation Threads Limited Direct Execution Basic Scheduling 2/5/18 CS 326: Operating Systems 2 Today s Schedule Process Creation
More informationData Races and Deadlocks! (or The Dangers of Threading) CS449 Fall 2017
Data Races and Deadlocks! (or The Dangers of Threading) CS449 Fall 2017 Data Race Shared Data: 465 1 8 5 6 209? tail A[] thread switch Enqueue(): A[tail] = 20; tail++; A[tail] = 9; tail++; Thread 0 Thread
More informationThreads. Jo, Heeseung
Threads Jo, Heeseung Multi-threaded program 빠른실행 프로세스를새로생성에드는비용을절약 데이터공유 파일, Heap, Static, Code 의많은부분을공유 CPU 를보다효율적으로활용 코어가여러개일경우코어에 thread 를할당하는방식 2 Multi-threaded program Pros. Cons. 대량의데이터처리에적합 - CPU
More informationChapter 4 Threads. Images from Silberschatz 03/12/18. CS460 Pacific University 1
Chapter 4 Threads Images from Silberschatz Pacific University 1 Threads Multiple lines of control inside one process What is shared? How many PCBs? Pacific University 2 Typical Usages Word Processor Web
More informationChapter 5: CPU Scheduling
COP 4610: Introduction to Operating Systems (Fall 2016) Chapter 5: CPU Scheduling Zhi Wang Florida State University Contents Basic concepts Scheduling criteria Scheduling algorithms Thread scheduling Multiple-processor
More informationCS533 Concepts of Operating Systems. Jonathan Walpole
CS533 Concepts of Operating Systems Jonathan Walpole Introduction to Threads and Concurrency Why is Concurrency Important? Why study threads and concurrent programming in an OS class? What is a thread?
More informationCS370 Operating Systems
CS370 Operating Systems Colorado State University Yashwant K Malaiya Spring 2019 Lecture 7 Threads Slides based on Text by Silberschatz, Galvin, Gagne Various sources 1 1 FAQ Amdahls law example: Person
More information4.8 Summary. Practice Exercises
Practice Exercises 191 structures of the parent process. A new task is also created when the clone() system call is made. However, rather than copying all data structures, the new task points to the data
More informationPOSIX Threads and OpenMP tasks
POSIX Threads and OpenMP tasks Jimmy Aguilar Mena February 16, 2018 Introduction Pthreads Tasks Two simple schemas Independent functions # include # include void f u n c t i
More informationPROCESS CONTROL BLOCK TWO-STATE MODEL (CONT D)
MANAGEMENT OF APPLICATION EXECUTION PROCESS CONTROL BLOCK Resources (processor, I/O devices, etc.) are made available to multiple applications The processor in particular is switched among multiple applications
More informationCS444 1/28/05. Lab 03
CS444 1/28/05 Lab 03 Note All the code that is found in this lab guide can be found at the following web address: www.clarkson.edu/class/cs444/cs444.sp2005/labs/lab03/code/ Threading A thread is an independent
More informationThreads. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University
Threads Jinkyu Jeong (jinkyu@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu EEE3052: Introduction to Operating Systems, Fall 2017, Jinkyu Jeong (jinkyu@skku.edu) Concurrency
More informationPOSIX Threads: a first step toward parallel programming. George Bosilca
POSIX Threads: a first step toward parallel programming George Bosilca bosilca@icl.utk.edu Process vs. Thread A process is a collection of virtual memory space, code, data, and system resources. A thread
More informationThreads need to synchronize their activities to effectively interact. This includes:
KING FAHD UNIVERSITY OF PETROLEUM AND MINERALS Information and Computer Science Department ICS 431 Operating Systems Lab # 8 Threads Synchronization ( Mutex & Condition Variables ) Objective: When multiple
More informationPthreads. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University
Pthreads Jin-Soo Kim (jinsookim@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu The Pthreads API ANSI/IEEE POSIX1003.1-1995 Standard Thread management Work directly on
More informationCISC2200 Threads Spring 2015
CISC2200 Threads Spring 2015 Process We learn the concept of process A program in execution A process owns some resources A process executes a program => execution state, PC, We learn that bash creates
More informationCS 261 Fall Mike Lam, Professor. Threads
CS 261 Fall 2017 Mike Lam, Professor Threads Parallel computing Goal: concurrent or parallel computing Take advantage of multiple hardware units to solve multiple problems simultaneously Motivations: Maintain
More informationA Thread is an independent stream of instructions that can be schedule to run as such by the OS. Think of a thread as a procedure that runs
A Thread is an independent stream of instructions that can be schedule to run as such by the OS. Think of a thread as a procedure that runs independently from its main program. Multi-threaded programs
More informationObject-Oriented Programming (OOP) Fundamental Principles of OOP
Object-Oriented Programming (OOP) O b j e c t O r i e n t e d P r o g r a m m i n g 1 Object-oriented programming is the successor of procedural programming. The problem with procedural programming is
More informationCSE 4/521 Introduction to Operating Systems
CSE 4/521 Introduction to Operating Systems Lecture 9 CPU Scheduling II (Scheduling Algorithms, Thread Scheduling, Real-time CPU Scheduling) Summer 2018 Overview Objective: 1. To describe priority scheduling
More informationCOSC 6374 Parallel Computation. Shared memory programming with POSIX Threads. Edgar Gabriel. Fall References
COSC 6374 Parallel Computation Shared memory programming with POSIX Threads Fall 2012 References Some of the slides in this lecture is based on the following references: http://www.cobweb.ecn.purdue.edu/~eigenman/ece563/h
More informationPThreads in a Nutshell
PThreads in a Nutshell Chris Kauffman CS 499: Spring 2016 GMU Logistics Today POSIX Threads Briefly Reading Grama 7.1-9 (PThreads) POSIX Threads Programming Tutorial HW4 Upcoming Post over the weekend
More informationCS 471 Operating Systems. Yue Cheng. George Mason University Fall 2017
CS 471 Operating Systems Yue Cheng George Mason University Fall 2017 1 Review: Sync Terminology Worksheet 2 Review: Semaphores 3 Semaphores o Motivation: Avoid busy waiting by blocking a process execution
More informationChapter 15 - C++ As A "Better C"
Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference
More informationProcesses, Threads, SMP, and Microkernels
Processes, Threads, SMP, and Microkernels Slides are mainly taken from «Operating Systems: Internals and Design Principles, 6/E William Stallings (Chapter 4). Some materials and figures are obtained from
More informationCS3157: Advanced Programming. Outline
CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching
More informationOperating System Labs. Yuanbin Wu
Operating System Labs Yuanbin Wu CS@ECNU Operating System Labs Project 4 Due: 10 Dec. Oral tests of Project 3 Date: Nov. 27 How 5min presentation 2min Q&A Operating System Labs Oral tests of Lab 3 Who
More informationYork University Lassonde School of Engineering Department of Electrical Engineering and Computer Science
York University Lassonde School of Engineering Department of Electrical Engineering and Computer Science Midterm EECS 3221.03Z Operating Systems Fundamentals Feb 26, 2015 (14:30-16:00) Section: EECS3221Z
More informationIntroduction to PThreads and Basic Synchronization
Introduction to PThreads and Basic Synchronization Michael Jantz, Dr. Prasad Kulkarni Dr. Douglas Niehaus EECS 678 Pthreads Introduction Lab 1 Introduction In this lab, we will learn about some basic synchronization
More informationConcurrent Server Design Multiple- vs. Single-Thread
Concurrent Server Design Multiple- vs. Single-Thread Chuan-Ming Liu Computer Science and Information Engineering National Taipei University of Technology Fall 2007, TAIWAN NTUT, TAIWAN 1 Examples Using
More informationInterview Questions of C++
Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.
More informationChapter 10. Threads. OS Processes: Control and Resources. A process as managed by the operating system groups together:
SFWR ENG 3BB4 Software Design 3 Concurrent System Design 2 SFWR ENG 3BB4 Software Design 3 Concurrent System Design 10.11 13 OS Processes: Control and Resources Chapter 10 Threads A process as managed
More information