12.1基于进程的并发编程
12.1.1基于进程的并发服务器
12.1.2进程的优劣
12.2基于I/O多路复用的并发编程
12.2.1基于I/O多路复用的并发事件驱动器
12.2.2I/O多路复用技术的优劣
优点
1、
2、
3、
4、
缺点
1、()
2、
12.3基于线程的并发编程
12.3.1线程执行模型
12.3.2Posix线程
12.3.3创建线程
12.3.4终止线程
12.3.5回收已终止线程的资源
12.3.6分离线程
12.3.7初始化线程
12.3.8基于线程的并发服务器
12.4多线程程序的共享变量
12.4.1线程内存模型
12.4.2将变量映射到内存
12.4.3共享变量
12.5用信号量同步线程
// /* WARING: This code is buggy */ #include "csapp.h"void thread(void vargp); / thread routine prototype /
/ globle shared variable /
volatile long cnt = 0; / counter /int main(int argc, char **argv)
{
long niters;
pthread_t tid1, tid2;</span><span style="color: #008000;">/*</span><span style="color: #008000;"> check input argument </span><span style="color: #008000;">*/</span> <span style="color: #0000ff;">if</span> (argc != <span style="color: #800080;">2</span><span style="color: #000000;">) { printf(</span><span style="color: #800000;">"</span><span style="color: #800000;">usage: %s <niters> </span><span style="color: #800000;">"</span>, argv[<span style="color: #800080;">0</span><span style="color: #000000;">]); exit(</span><span style="color: #800080;">0</span><span style="color: #000000;">); } niters </span>= atoi(argv[<span style="color: #800080;">1</span><span style="color: #000000;">]); </span><span style="color: #008000;">/*</span><span style="color: #008000;"> create threads and wait for them to finish </span><span style="color: #008000;">*/</span><span style="color: #000000;"> pthread_create(</span>&tid1, NULL, thread, &<span style="color: #000000;">niters); pthread_create(</span>&tid2, NULL, thread, &<span style="color: #000000;">niters); pthread_join(tid1, NULL); pthread_join(tid2, NULL); </span><span style="color: #008000;">/*</span><span style="color: #008000;"> check result </span><span style="color: #008000;">*/</span> <span style="color: #0000ff;">if</span> (cnt != (<span style="color: #800080;">2</span> *<span style="color: #000000;"> niters)) printf(</span><span style="color: #800000;">"</span><span style="color: #800000;">BOOM! cnt = %1d </span><span style="color: #800000;">"</span><span style="color: #000000;">, cnt); </span><span style="color: #0000ff;">else</span><span style="color: #000000;"> printf(</span><span style="color: #800000;">"</span><span style="color: #800000;">OK cnt = %1d </span><span style="color: #800000;">"</span><span style="color: #000000;">, cnt); exit(</span><span style="color: #800080;">0</span><span style="color: #000000;">);
}
/ thread routine /
void *thread(void *vargp)
{
long i, niters = *((long *)vargp);</span><span style="color: #0000ff;">for</span> (i = <span style="color: #800080;">0</span>; i < niters; i++<span style="color: #000000;">) cnt</span>++<span style="color: #000000;">; </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> NULL;
}
//
12.5.1进度图
12.5.2信号量
12.5.3使用信号量实现互斥
12.5.4利用信号量来调度共享资源
1.生产者-消费者问题
2.读者-写者问题
12.5.5综合:基于预线程化的并发服务器
12.6使用线程提高并行性
刻画并行程序的性能