hw4 due next Thursday
final exam March 18th (Wednesday)
sockets revisited
processes & threads
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]
standard Unix abstractions: files, sockets, pipes, …
/dev/[u]random: cat /dev/random | xxd
procfs: /proc/cpuinfo
see also lec 3: /proc/PID/maps
problem: one connection at a time
goal: handle multiple connections
approaches: multiplexing / virtualization
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
processes
threads
OS scheduling
example: Apache
virtualization: processor & address space
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
: concurrency through virtualization
add a global counter?
separate address spaces
reliable: crash in one process won’t affect others
sharing needs more work: inter-process communication
performance concerns
(lightweight) virtualization: processor
share the same address space
separate stack
easy to communicate; need synchronization
API: pthreads, C11 threads, C++11 threads
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
<thread>
: detach/join
<atomic>
: shared data
echosrv-c++thread.cc: w/ global counter
high-level interface: <future>
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)