A POSIX thread (pthread) Tutorial

A POSIX thread (pthread) Tutorial

P4: Multithreaded Programming Zhenxiao Luo CS537 Spring 2010 Outline Motivation Thread Basics Thread Operations Thread Synchronizations Pthread: counter, HashTable SpinLock: SpinLock, SpinCounter, SpinList, SpinHash

Setting Environment Variable setenv LD_LIBRARY_PATH ${LD_LIBRARY_PATH}:. As done in P3 Or, you may have: error while loading shared libraries: libcounter.so: cannot open shared object file: No such file or directory Motivation: Why Use Threads? To Execute Software Faster Improve performance through parallel or

distributed computing Processes are too expensive Threads are effective on both multiprocessor systems and uniprocessor systems Thread Basics All threads within a process share the same address space Threads in the same process share: Process instructions open files (descriptors)

current working directory Each thread has a unique: Thread ID set of registers, stack pointer priority Thread Operations Thread Creation int pthread_create(pthread_t * thread, const pthread_attr_t * attr,

void * (*start_routine)(void *), void *arg); Thread Termination void pthread_exit(void *retval); Thread Synchronization mutexes - Mutual exclusion lock joins - Make a thread wait till others are complete condition variables wait() and signal() Pthread Counter pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;

static int global_counter = 0; void Counter_Init(){ global_counter = 0; } void Counter_Increment(){ pthread_mutex_lock( &mutex1 ); global_counter++; pthread_mutex_unlock( &mutex1 ); } Pthread HashTable

struct hash_element{ int number; struct hash_element *next; }; struct hash_bucket{ int elemCount; struct hash_element *head; }; static struct hash_bucket *hash_buckets; static int g_numOfBuckets; pthread_mutex_t *mutexArray;

Hash Table - Init void Hash_Init(int buckets){ int i = 0; hash_buckets = malloc(buckets * sizeof(struct hash_bucket)); g_numOfBuckets = buckets; mutexArray = (pthread_mutex_t*)malloc(buckets * sizeof(pthread_mutex_t)); for (i = 0; i < buckets; i++) { hash_buckets[i].head = NULL; hash_buckets[i].elemCount = 0; pthread_mutex_init(&(mutexArray[i]), NULL);

} } Hash Table - Insert Get BucketNumber: int bucketNum = x % g_numOfBuckets; Traverse the list of elements: If x is found, return -1 If x is not found, create new element, insert into the end of the list

Remember to allocate memory for new element Remember to add mutex lock when inserting to the list Hash Table - Remove Get BucketNumber: int bucketNum = x % g_numOfBuckets; Traverse the list of elements: If x is not found, return -1 If x is found, remove it from the list, update pointers

Remember to add mutex lock when removing element from the list SpinLock TestAndSet: xchg(volatile unsigned int *addr, unsigned int newval)

Typedef struct spinlock_t { int flag; } spinlock_t; void spinlock_acquire(spinlock_t *lock) { while (xchg(&lock->flag, 1) == 1); // spin wait} SpinLock Cond void spinlock_release(spinlock_t *lock) { lock->flag = 0;

} void spinlock_init(spinlock_t *lock) { lock->flag = 0; } SpinCounter

typedef struct __counter_t { int counter; spinlock_t lock; } counter_t;

void Counter_Increment(counter_t *c) { spinlock_acquire(&c->lock); c->counter++; spinlock_release(&c->lock); SpinList typedef struct __listnode_t { unsigned int key; void *value; struct __listnode_t *next;

} node; typedef struct __list_t { node *head; spinlock_t lock; } list_t; SpinList Cond void List_Insert(list_t *l, void *element, unsigned int key) { node* tmp = malloc(sizeof(node)); tmp->key = key; tmp->value = element;

spinlock_acquire(&l->lock); tmp->next = l->head; l->head = tmp; spinlock_release(&l->lock); } SpinHash typedef struct __hash_t { int numbuckets; // # of buckets list_t *hash_buckets; } hash_t;

void Hash_Insert(hash_t *h, void *element, unsigned int key) { // compute hash; int index = key % h->numbuckets; List_Insert(&h->hash_buckets[index], element, key); } void Hash_Remove(hash_t *h, unsigned int key) { // compute hash; int index = key % h->numbuckets; List_Remove(&h->hash_buckets[index], key);

Recently Viewed Presentations

  • Students and tutors as co-creators of knowledge: enhancing ...

    Students and tutors as co-creators of knowledge: enhancing ...

    'An occupation is an activity or group of Activities that engages a person in everyday life, has personal meaning and provides structure to time' (COT, 2004) Occupation is a threshold concept that should be embedded in the occupational therapy curriculum...
  • CS1313 Search Lesson

    CS1313 Search Lesson

    Search Lesson. CS1313 Fall 2018. Linear Search. Linear search. means looking at each element of the array, in turn, until you find the target value.-23. 97. 18. 21. 5-86
  • F E H R E ! P SU

    F E H R E ! P SU

    Superheroes give back! Event Blurb We Used This Year on Our Events Calendar/Newsletters: "Dress as your favorite superhero or decorate a mask and cape at the party, make a craft to donate to a local charity, and have fun at...
  • Welcome to the College of Science! - Texas State University

    Welcome to the College of Science! - Texas State University

    Welcome to the College of Science and Engineering! via the Online Toolkit. Set up your Texas State email. You will receive information regarding: Academic deadlines. Necessary course evaluations. Graduation. Registration holds. University closures and urgent communications.
  • Introduction to Factor Analysis - Medical University of South ...

    Introduction to Factor Analysis - Medical University of South ...

    Factor Analysis Elizabeth Garrett-Mayer, PhD Georgiana Onicescu, ScM Cancer Prevention and Control Statistics Tutorial July 9, 2009 Motivating Example: Cohesion in Dragon Boat paddler cancer survivors Dragon boat paddling is an ancient Chinese sport that offers a unique blend of...
  • Common variants and their contribution to heritability (GWAS

    Common variants and their contribution to heritability (GWAS

    Genetic architecture, selection and heritability [Zeng et al. 2018 Nature Genetics] Known unknowns. Can we recover pedigree heritability from WGS data in a random sample from the population? How much trait variation is due to structural variation not captured by...
  • Technical Problems and Resolutions

    Technical Problems and Resolutions

    Resources and Resolutions James Milward 27/6/2006 A Brief Introduction to RHUL Psychology Royal Holloway Psychology Department consists of: 37 Academic Staff 30 Postgraduate / Research Staff 10 Administrative Staff 8 Technical Staff And a various array of systems to support...
  • The Water Cycle - Colorado FFA

    The Water Cycle - Colorado FFA

    In large forests, an enormous amount of water will transpire through leaves. Steps to creating a water system Materials needed: Mason Jar Latex Glove Heat source (microwave or Bunsen burner) One head of lettuce Moisture tester Steps: Test the moisture...