Escolar Documentos
Profissional Documentos
Cultura Documentos
CS 370
Spring-11
What is thread?
A single sequential flow of control within a program
Lightweight process?
Advantages
less time to create and destroy threads compared to processes
Disadvantage
Resources are shared!! Be Cautious!!
Implementing Threads
User Space
Kernel Space
Advantages
Even in those OS which don't support threads
Scales better
Disadvantages
What if a thread has a blocking system call
Advantages
No runtime system needed
Disadvantages
Greater cost of creation and destruction of thread
Scheduler Activation
mimic the functionality of kernel threads but still have better
performance and greater flexibility as in user space
How?
Kernel assigns a number of virtual processors to each process.
Upcall
Kernel notifies the run-time system when a blocking call is
made.
Programming Project
Threads!
pthread_create
#include<pthread.h>
int pthread_create(pthread_t *restrict thread, const pthread_attr_t *restrict attr, void *(*start_routine)
(void*), void *restrict arg);
*thread :
*attr :
*start_routine :
*arg :
pthread_join
This call will block until the specified thread has completed.
#include <pthread.h>
thead :
value_ptr:
pthread_exit
Used to end the threads execution and return a value (if needed) to the join function.
#include <pthread.h>
*value_ptr:
Threads Example
#include <stdio.h>
#include <pthread.h>
int main() {
.
pthread_t threadIds[5]
}
void calledFxn(void *arg) {
. //perform necessary tasks here
pthread_exit(NULL);
}
Race Condition
A race condition is an undesirable situation that occurs when a device or system attempts to
perform two or more operations at the same time, but because of the nature of the device or
system, the operations must be done in the proper sequence in order to be done correctly.
There are two threads (T1 and T2) that increment a global variable. Lets say these operations take
place:
Global integer = 0
But from this example the global integer has the value 1
Critical Section
A piece of code that accesses a shared resource that must not be concurrently accessed by
more than one thread of execution.
sem_init
#include <semaphore.h>
*sem:
pshared :
used when sharing semaphores between processes, we will use 0 (not sharing
between processes)
Value:
initial value of the semaphore. Can be thought of how many open resources there
sem_wait
#include <semaphore.h>
*sem:
If the critical section is not available the call will block until it is available (another threads calls
sem_post).
sem_post
#include <semaphore.h>
*sem:
Semaphore Example..
#include <semaphore.h>
sem_t sem;
int main() {
..
sem_init(&sem, 0, 1); //initializing semaphore so that atmost one thread can be inside the critical section.
//create threads & call a function for threads to execute
.// join the threads
}
void callAfunction(void *threadArg) {
//