Chapter 4. Threads & Concurrency
Chapter 4. Threads & Concurrency
Chapter 4
Threads & Concurrency
Yunmin Go
School of CSEE
Agenda
◼ Overview
◼ Multicore Programming
◼ Multithreading Models
◼ Thread Libraries
◼ Implicit Threading
◼ Threading Issues
◼ Signal
◼ Operating System Examples
◼ A thread is comprised of
◼ Thread ID, program counter, register set, stack, etc.
Threads & Concurrency - 4
Single and Multithreaded Processes
◼ Multithreading Models
◼ Many-to-One
◼ One-to-One
◼ Many-to-Many
https://man7.org/linux/man-pages/man3/pthread_attr_init.3.html
https://man7.org/linux/man-pages/man3/pthread_exit.3.html Threads & Concurrency - 27
Example: Pthreads
#include <stdio.h> // thread will execute in this function
#include <pthread.h> void *thread_summation(void * arg)
{
void *thread_summation(void * arg); int start = ((int*)arg)[0];
int sum = 0; int end = ((int*)arg)[1];
◼ Creating a thread
Thread worker = new Thread(new Task());
worker.start(); 1. It allocates memory and initializes a new
thread in JVM.
2. It calls the run() method, making the thread
◼ Waiting on a thread eligible to be run by the JVM.
try {
worker.join();
} catch (InterruptedException e) {
}
Thread Pool
Thread Thread
Thread Thread
Thread Thread
Threads & Concurrency - 39
Java Thread Pools
◼ Supported by Java executor framework in java.util.concurrent
package
◼ Three factory methods for creating thread pools in Executors class:
◼ static ExecutorService newSingleThreadExecutor()
◼ Creates a pool of size 1
◼ static ExecutorService newFixedThreadPool(int size)
◼ Creates a thread pool with a specified number of threads
◼ static ExecutorService newCachedThreadPool()
◼ Creates an unbounded thread pool, reusing in many instances
/* sequential code */
return 0;
}