apue学习笔记(第十一章 线程)

本章将进一步深入理解进程,了解如何使用多个控制线程(简单得说就是线程)在单进程环境中执行多个任务。

 

 

线程概念

每个线程都包含有表示执行环境所必须的信息:线程ID、一组寄存器值、栈、调度优先级和策略、信号屏蔽字、errno变量以及线程私有数据。

一个进程的所有信息对该进程的所有线程都是共享的,包括可执行程序的代码、程序的全局内存和堆内存、栈以及文件描述符。

 

 

线程标识

每个线程都有一个线程ID,线程ID只有在它所属的进程上下文中才有意义。

可以使用下面函数来对两个线程ID进行比较

#include <pthread.h>
int pthread_equal(pthread_t tid1,pthread_t tid2);

可以通过pthread_self函数获得自身的线程ID

#include <pthread.h>
pthread_t pthread_self(void);

 

 

 

线程创建

#include <pthread.h>
int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict attr,void *(*start_rtn)(void *),void *restrict arg);

当pthread_create成功返回时,新创建线程的线程ID会被设置成tidp指向的内存空间。

attr属性用于定制各种不同的线程属性。

新创建的线程从start_rtn函数的地址开始运行,该函数只有一个无类型指针参数arg。

下面程序将演示线程的创建,打印出进程ID、新线程的线程ID以及初始线程的线程ID:

 1 #include "apue.h"
 2 #include <pthread.h>
 3 
 4 pthread_t ntid;
 5 
 6 void
 7 printids(const char *s)
 8 {
 9     pid_t        pid;
10     pthread_t    tid;
11 
12     pid = getpid();
13     tid = pthread_self();
14     printf("%s pid %lu tid %lu (0x%lx)\n", s, (unsigned long)pid,
15       (unsigned long)tid, (unsigned long)tid);
16 }
17 
18 void *
19 thr_fn(void *arg)
20 {
21     printids("new thread: ");
22     return((void *)0);
23 }
24 
25 int
26 main(void)
27 {
28     int        err;
29 
30     err = pthread_create(&ntid, NULL, thr_fn, NULL);
31     if (err != 0)
32         err_exit(err, "can't create thread");
33     printids("main thread:");
34     sleep(1);
35     exit(0);
36 }
View Code

线程创建时并不能保证哪个线程先会运行:是新创建的线程,还是调用线程。本程序让主线程休眠,确保新线程有机会运行。

 

 

 

线程终止

如果进程中任意线程调用了exit、_Exit或者_exit,那么整个进程就会终止。

单个线程可以通过3种方式退出,因此可以在不终止整个进程的情况下,停止它的控制流。

1 线程可以简单地从启动例程中返回,返回值的线程的退出码。

2 线程可以被同一进程中的其他线程取消。

3 线程调用pthread_exit。

#include <pthread.h>
void pthread_exit(void *rval_ptr);

rval_ptr参数是一个无类型指针,进程中的其他线程也可以通过调用pthread_join函数访问到这个指针

#include <pthread.h>
int pthread_join(pthread_t thread,void **rval_ptr);

调用pthread_join后,调用线程将一直阻塞,直到指定的线程退出。

如果线程简单地从它的启动例程返回,rval_ptr将包含返回码。如果线程被取消,由rval_ptr指定的内存单元就设置成PTHREAD_CANCELED。

下面演示如何获取已终止线程的退出码:

 1 #include "apue.h"
 2 #include <pthread.h>
 3 
 4 void *
 5 thr_fn1(void *arg)
 6 {
 7     printf("thread 1 returning\n");
 8     return((void *)1);
 9 }
10 
11 void *
12 thr_fn2(void *arg)
13 {
14     printf("thread 2 exiting\n");
15     pthread_exit((void *)2);
16 }
17 
18 int
19 main(void)
20 {
21     int            err;
22     pthread_t    tid1, tid2;
23     void        *tret;
24 
25     err = pthread_create(&tid1, NULL, thr_fn1, NULL);
26     if (err != 0)
27         err_exit(err, "can't create thread 1");
28     err = pthread_create(&tid2, NULL, thr_fn2, NULL);
29     if (err != 0)
30         err_exit(err, "can't create thread 2");
31     err = pthread_join(tid1, &tret);
32     if (err != 0)
33         err_exit(err, "can't join with thread 1");
34     printf("thread 1 exit code %ld\n", (long)tret);
35     err = pthread_join(tid2, &tret);
36     if (err != 0)
37         err_exit(err, "can't join with thread 2");
38     printf("thread 2 exit code %ld\n", (long)tret);
39     exit(0);
40 }
View Code

 

线程可以通过调用pthread_cancel函数来请求取消同一进程中的其他进程。

#include <pthread.h>
int pthread_cancel(pthread_t tid);

pthread_cancel并不等待线程终止,它仅仅提出请求,线程可以选择忽略取消或者控制如何被取消。

线程可以安排它退出时需要调用的函数,这与进程在退出时可以用atexit函数安排退出时类似的。

如果线程是通过从它的启动例程中退出返回而终止的话,它的清理处理程序就不会被调用。

#include <pthread.h>
void pthread_cleanup_push(void (*rtn)(void *),void *arg);
void pthread_cleanup_pop(int execute);

如果execute参数设置为非0,则调用并删除上次pthread_cleanup_push调用建立的清理处理程序。

如果execute参数为0,则清理函数将不被调用(只删除)。

我们可以调用pthread_detach分离线程。

#include <pthread.h>
int pthread_detach(pthread_t tid);

 

 

 

线程同步

当一个线程可以修改的变量,其他线程可以读取或者修改的时候,我们就需要对这些线程进行同步,确保他们在访问变量的存储内容时不会访问到无效的值。

为了解决这个问题,线程不得不使用锁,同一时间只允许一个线程访问该变量。

 

 

互斥量

可以使用pthread的互斥接口来保护数据,确保同一时间只有一个线程访问数据。

互斥量从本质上说是一把锁,在访问共享资源前对互斥量进行设置(加锁),在访问完成后释放(解锁)互斥量。

互斥变量使用pthread_mutex_t数据类型表示的。在使用之前,必须对它进行初始化,如果动态分配互斥量,在释放内存前需要调用pthread_mutex_destroy。

#include <pthread.h>
int pthread_mutex_init(pthread_mutex_t *restrict mutex,const pthread_mutexattr_t *restrict attr);
int pthread_mutex_destroy(pthread_mutex_t *mutex);

要用默认的属性初始化互斥量,只需把attr设为NULL,也可以把互斥量设置为常量PTHREAD_MUTEX_INITIALIZER(只适用于静态分配的互斥量)进行初始化。

互斥量有以下3种功能

#include <pthread.h>
int pthread_mutex_lock(pthread_mutex_t *mutex); 
int pthread_mutex_trylock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);

可以使用pthread_mutex_lock对互斥量进行加锁,如果互斥量已经上锁,调用线程将阻塞直到互斥量被解锁。

可以使用pthread_mutex_unlock对互斥量解锁。

如果不希望被阻塞,可以使用pthread_mutex_trylock尝试对互斥量进行加锁。如果互斥量处于未锁住状态,则锁住互斥量,否则返回EBUSY。

 

 

 

避免死锁

如果线程试图对同一个互斥量加锁两次,那么它自身就会陷入死锁状态。

如果两个线程以相反的顺序锁住两个互斥量,也会导致死锁,两个线程都无法向前运行。

在同时需要两个互斥量时,让他们以相同的顺序加锁,这样可以避免死锁。

 

 

 

函数pthread_mutex_timedlock

与pthread_mutex_lock不同的是,pthread_mutex_timedlock允许绑定线程阻塞时间,如果超过时间值,pthread_mutex_timedlock不会对互斥量进行加锁,而是返回错误码ETIMEDOUT。

#include <pthread.h>
#include <time.h>
int pthread_mutex_timedlock(pthread_mutex_t *restrict mutex,const struct timespec *restrict tsptr);

下面给出如何用pthread_mutex_timedlock避免永久阻塞

 1 #include "apue.h"
 2 #include <pthread.h>
 3 
 4 int
 5 main(void)
 6 {
 7     int err;
 8     struct timespec tout;
 9     struct tm *tmp;
10     char buf[64];
11     pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
12 
13     pthread_mutex_lock(&lock);
14     printf("mutex is locked\n");
15     clock_gettime(CLOCK_REALTIME, &tout);
16     tmp = localtime(&tout.tv_sec);
17     strftime(buf, sizeof(buf), "%r", tmp);
18     printf("current time is %s\n", buf);
19     tout.tv_sec += 10;    /* 10 seconds from now */
20     /* caution: this could lead to deadlock */
21     err = pthread_mutex_timedlock(&lock, &tout);
22     clock_gettime(CLOCK_REALTIME, &tout);
23     tmp = localtime(&tout.tv_sec);
24     strftime(buf, sizeof(buf), "%r", tmp);
25     printf("the time is now %s\n", buf);
26     if (err == 0)
27         printf("mutex locked again!\n");
28     else
29         printf("can't lock mutex again: %s\n", strerror(err));
30     exit(0);
31 }
View Code

这个程序对已有的互斥量加锁,演示了pthread_mutex_timedlock是如何工作的。

 

 

读写锁

读写锁与互斥量类似,不过读写锁允许更高的并行性。

读写锁可以有3种状态:读模式下加锁状态,写模式下加锁状态,不加锁状态。

一次只有一个线程可以占有写模式的读写锁,但是多个线程可以同时占有读模式的读写锁。

1. 当读写锁是写加锁状态时,在这个锁被解锁之前,所有试图对这个所加锁的线程都会被阻塞。

2. 当读写锁是读加锁状态时,所有试图以读模式对它进行加锁的线程都可以得到访问权,但是任何希望以写模式对此进行加锁的线程都会阻塞,知道所有的线程释放它们的读锁为止。

读写锁在使用之前必须初始化,在释放他们底层的内存之前必须销毁。

#include <pthread.h>
int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock,const pthread_rwlockattr_t *restrict attr);
int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);

下面是读写锁的3种用法

#include <pthread.h>
int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);

与互斥量一样,读写锁定义了下面两个函数

#include <pthread.h>
int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_tryrwrock(pthread_rwlock_t *rwlock);

 

 

 

带有超时的读写锁

与互斥量一样,有两个带有超时的速写锁加锁函数

#include <pthread.h>
#include <time.h>
int pthread_rwlock_timedrdlock(pthread_rwlock_t *restrict rwlock,const struct timespec *restrict tsptr);
int pthread_rwlock_timedwrlock(pthread_rwlock_t *restrict rwlock,const struct timespec *restrict tsptr);

 

 

 

条件变量

在使用条件变量之前,必须对它进行初始化,在释放底层的内存空间之前,可以使用pthread_cond_destroy函数对条件变量进行反初始化

#include <pthread.h>
int pthread_cond_init(pthread_cond_t *restrict cond,const pthread_condattr_t *restrict attr);
int pthread_cond_destroy(pthread_cond_t *cond);

条件本身是由互斥量保护的。线程在改变条件状态之前必须首先锁住互斥量,然后调用下面函数等待条件变量为真。

#include <pthread.h>
int pthread_cond_wait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex);
int pthread_cond_timedwait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex,const struct timespec *restrict tsptr);

调用者把锁住的互斥量传给函数,函数自动把调用线程放到等待条件的线程列表上,对互斥量解锁。pthread_cond_wati返回时,互斥量再次被锁住。

pthread_cond_timedwait则添加了一个超时值,如果超过到期时条件还是没有出现,则函数重新获取互斥量,然后返回ETIMEDOUT。

两个函数调用成功返回时,线程需要重新计算条件,因为另一个线程可能已经在运行并改变条件。

下面函数用于通知线程条件已经满足:

#include <pthread.h>
int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t *cond);

phread_cond_signal函数至少能唤醒一个等待该条件的线程,而pthread_cond_broadcast函数则能唤醒等待该条件的所有线程。

下面将结合条件变量和互斥量对线程进行同步

 1 #include <pthread.h>
 2 
 3 struct msg {
 4     struct msg *m_next;
 5     /* ... more stuff here ... */
 6 };
 7 
 8 struct msg *workq;
 9 
10 pthread_cond_t qready = PTHREAD_COND_INITIALIZER;
11 
12 pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;
13 
14 void
15 process_msg(void)
16 {
17     struct msg *mp;
18 
19     for (;;) {
20         pthread_mutex_lock(&qlock);
21         while (workq == NULL)
22             pthread_cond_wait(&qready, &qlock);
23         mp = workq;
24         workq = mp->m_next;
25         pthread_mutex_unlock(&qlock);
26         /* now process the message mp */
27     }
28 }
29 
30 void
31 enqueue_msg(struct msg *mp)
32 {
33     pthread_mutex_lock(&qlock);
34     mp->m_next = workq;
35     workq = mp;
36     pthread_mutex_unlock(&qlock);
37     pthread_cond_signal(&qready);
38 }
View Code

 

 

 

自旋锁

自旋锁与互斥量类似,但它不是通过休眠使进程阻塞,而是在获取锁之前一直处于忙等(自旋)阻塞状态。

自旋锁可用于以下情况:锁被持有的时间短,而且线程并不希望在重新调度上花费太多的成本。

自旋锁的接口与互斥量的接口类似,提供了以下的5个函数。

#include <pthread.h>
int pthread_spin_init(pthread_spinlock_t *lock,int pshared);
int pthread_spin_destroy(pthread_spinlock_t *lock);

int pthread_spin_lock(pthread_spinlock_t *lock);
int pthread_spin_trylock(pthread_spinlock_t *lock);
int pthread_spin_unlock(pthread_spinlock_t *lock);

 

 

屏障

屏障是用户协调多个线程并行工作的同步机制。

屏障允许每个线程等待,直到有的合作线程到达某一点,然后从该点继续执行。pthread_join函数就是一种屏障,允许一个线程等待,直到另一个线程退出。

可以使用下面函数对屏障进行初始化跟反初始化

#include <pthread.h>
int pthread_barrier_init(pthread_barrier_t *restrict barrier,const pthread_barrierattr_t *restrict attr,unsigned int count);
int pthread_barrier_destroy(pthread_barrier_t *barrier);

count参数可以用来指定在允许所有线程继续运行之前,必须到达屏障的线程数目。

可以使用pthread_barrier_wait函数来表明,线程已经完成工作,准备等所有其他线程赶上来

#include <pthread.h>
int pthread_barrier_wait(pthread_barrier_t *barrier);

调用pthread_barrier_wait的线程在屏障计数(调用pthread_barrier_init时设定)未满足条件时,会进入休眠状态。

如果该线程是最后一个调用pthread_barrier_wait的线程,就满足了屏障计数,所有的线程都被唤醒。

下面给出在一个任务上合作的多个线程之间如何用屏障进行同步

  1 #include "apue.h"
  2 #include <pthread.h>
  3 #include <limits.h>
  4 #include <sys/time.h>
  5 
  6 #define NTHR   8                /* number of threads */
  7 #define NUMNUM 8000000L            /* number of numbers to sort */
  8 #define TNUM   (NUMNUM/NTHR)    /* number to sort per thread */
  9 
 10 long nums[NUMNUM];
 11 long snums[NUMNUM];
 12 
 13 pthread_barrier_t b;
 14 
 15 #ifdef SOLARIS
 16 #define heapsort qsort
 17 #else
 18 extern int heapsort(void *, size_t, size_t,
 19                     int (*)(const void *, const void *));
 20 #endif
 21 
 22 /*
 23  * Compare two long integers (helper function for heapsort)
 24  */
 25 int
 26 complong(const void *arg1, const void *arg2)
 27 {
 28     long l1 = *(long *)arg1;
 29     long l2 = *(long *)arg2;
 30 
 31     if (l1 == l2)
 32         return 0;
 33     else if (l1 < l2)
 34         return -1;
 35     else
 36         return 1;
 37 }
 38 
 39 /*
 40  * Worker thread to sort a portion of the set of numbers.
 41  */
 42 void *
 43 thr_fn(void *arg)
 44 {
 45     long    idx = (long)arg;
 46 
 47     heapsort(&nums[idx], TNUM, sizeof(long), complong);
 48     pthread_barrier_wait(&b);
 49 
 50     /*
 51      * Go off and perform more work ...
 52      */
 53     return((void *)0);
 54 }
 55 
 56 /*
 57  * Merge the results of the individual sorted ranges.
 58  */
 59 void
 60 merge()
 61 {
 62     long    idx[NTHR];
 63     long    i, minidx, sidx, num;
 64 
 65     for (i = 0; i < NTHR; i++)
 66         idx[i] = i * TNUM;
 67     for (sidx = 0; sidx < NUMNUM; sidx++) {
 68         num = LONG_MAX;
 69         for (i = 0; i < NTHR; i++) {
 70             if ((idx[i] < (i+1)*TNUM) && (nums[idx[i]] < num)) {
 71                 num = nums[idx[i]];
 72                 minidx = i;
 73             }
 74         }
 75         snums[sidx] = nums[idx[minidx]];
 76         idx[minidx]++;
 77     }
 78 }
 79 
 80 int
 81 main()
 82 {
 83     unsigned long    i;
 84     struct timeval    start, end;
 85     long long        startusec, endusec;
 86     double            elapsed;
 87     int                err;
 88     pthread_t        tid;
 89 
 90     /*
 91      * Create the initial set of numbers to sort.
 92      */
 93     srandom(1);
 94     for (i = 0; i < NUMNUM; i++)
 95         nums[i] = random();
 96 
 97     /*
 98      * Create 8 threads to sort the numbers.
 99      */
100     gettimeofday(&start, NULL);
101     pthread_barrier_init(&b, NULL, NTHR+1);
102     for (i = 0; i < NTHR; i++) {
103         err = pthread_create(&tid, NULL, thr_fn, (void *)(i * TNUM));
104         if (err != 0)
105             err_exit(err, "can't create thread");
106     }
107     pthread_barrier_wait(&b);
108     merge();
109     gettimeofday(&end, NULL);
110 
111     /*
112      * Print the sorted list.
113      */
114     startusec = start.tv_sec * 1000000 + start.tv_usec;
115     endusec = end.tv_sec * 1000000 + end.tv_usec;
116     elapsed = (double)(endusec - startusec) / 1000000.0;
117     printf("sort took %.4f seconds\n", elapsed);
118     for (i = 0; i < NUMNUM; i++)
119         printf("%ld\n", snums[i]);
120     exit(0);
121 }
View Code

在这个实例中,使用8个线程分解了800万个数的排序工作。每个线程用堆排序算法对100万个数进行排序,然后主线程调用一个函数对这些结果进行合并。

  

 

posted @ 2015-07-13 17:46  Runnyu  阅读(1392)  评论(0编辑  收藏  举报