Presentation is loading. Please wait.

Presentation is loading. Please wait.

Threads? Threads allow us to have multiple tasks active at the same time in one executable –think of a server handling multiple connections Each thread.

Similar presentations


Presentation on theme: "Threads? Threads allow us to have multiple tasks active at the same time in one executable –think of a server handling multiple connections Each thread."— Presentation transcript:

1

2 Threads? Threads allow us to have multiple tasks active at the same time in one executable –think of a server handling multiple connections Each thread has its own stack Each thread has its own instruction pointer Each thread has access to shared data Why? –See server example above –Parallelism – may be able to speed up some computation (sum of X numbers) multi-CPU system or dual/quad core CPU

3 Webserver Thread 0 int conns=0; main() { while(1) { waitForConnection() runThread(threadMain) } Thread 1 threadMain() { int run=1; conns++; while(run) { recv() send() } close() conns -- ; } Web browser Thread 2 threadMain() { int run=1; conns++; while(run) { recv() send() } close() conns -- ; } Thread 3 threadMain() { int run=1; conns++; while(run) { recv() send() } close() conns -- ; } Can you spot the problem(s)?

4 Synchronization Mutex: Mutually exclusive –only one thread can have it –use it to guard shared data –lock/unlock –how will this fix the previous example?

5 Pthreads POSIX threads –Portable Operating System Interface for uniX –this is a particular API to a threading library specifies the functions to provide implementation is up to the developer #include pthread_t thread1; pthread_mutex_t guardConns;

6 pthreads int pthread_create (pthread_t* thread, pthread_attr_t * attr, void * (*start_routine)(void *), void * arg) pthread_attr_t sets attributes of the thread, can be set to NULL for now start_routine should be a void* foo(void*) int pthread_join( pthread_t th, void **thread_return) return value of the thread is stored in thread_return (if it is not NULL) void pthread_exit(void*)

7 Mutexes int pthread_mutex_init( pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr) mutexattr may be NULL to accept the default settings int pthread_mutex_lock(pthread_mutex_t *mutex) int pthread_mutex_unlock(pthread_mutex_t *mutex)


Download ppt "Threads? Threads allow us to have multiple tasks active at the same time in one executable –think of a server handling multiple connections Each thread."

Similar presentations


Ads by Google