lec 20: concurrency intro

administrivia

hw4 due next Thursday

final exam March 18th (Wednesday)

today’s plan

sockets revisited

processes & threads

client & server sockets

getaddrinfo: convert hostname port to sockaddr

socket / connect

send a file over network: read/write, mmap, or sendfile

bind / listen / accept

(see ex15/ex16 reference solutions)

_POSIX_C_SOURCE: see Section 3 or gcc manual (macros, -std)

[draw front-end/back-end servers]

files & file descriptors

standard Unix abstractions: files, sockets, pipes, …

/dev/[u]random: cat /dev/random | xxd

procfs: /proc/cpuinfo

see also lec 3: /proc/PID/maps

echo server

lec 18: echo server

problem: one connection at a time

goal: handle multiple connections

approaches: multiplexing / virtualization

concurrency: multiplexing

event-driven

select/poll

epoll (Linux), kqueue (BSD), I/O completion ports (Windows)

hard to program: your application is the scheduler

examples: nginx, node.js

concurrency: virtualization

processes

threads

OS scheduling

example: Apache

processes

CSE 351: processes

virtualization: processor & address space

fork

pid_t fork(void);

returns -1 if error, 0 in child process, pid in parent process

child: inherits a copy of parent’s file descriptors

parent: should wait on child or signal(SIGCHLD, SIG_IGN)

Linux: actually uses clone, inspired by Plan 9

fork: echo server

fork: concurrency through virtualization

echosrv-fork.c

add a global counter?

fork-based servers

separate address spaces

reliable: crash in one process won’t affect others

sharing needs more work: inter-process communication

performance concerns

threads

(lightweight) virtualization: processor

share the same address space

separate stack

easy to communicate; need synchronization

API: pthreads, C11 threads, C++11 threads

pthreads

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                   void *(*start_routine) (void *), void *arg);
int pthread_detach(pthread_t thread);
int pthread_join(pthread_t thread, void **retval);

include <pthread.h>; link with -lpthread

call pthread_detach or pthread_join to release its resources

pass arg to start_routine: lifetime & pack multiple values

echosrv-pthreads.c

C++11 threads

<thread>: detach/join

<atomic>: shared data

echosrv-c++thread.cc: w/ global counter

high-level interface: <future>

ex17

ex17: use 4 threads to compute the sum of array elements

pthread_create: start threads

pass multiple values to pthread_create: use a struct

call pthread_join to wait for completion

or use C++11 async (example)