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

线程概念

每个线程都包含有表示执行环境所必须的信息:线程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:

 #include "apue.h"
#include <pthread.h> pthread_t ntid; void
printids(const char *s)
{
pid_t pid;
pthread_t tid; pid = getpid();
tid = pthread_self();
printf("%s pid %lu tid %lu (0x%lx)\n", s, (unsigned long)pid,
(unsigned long)tid, (unsigned long)tid);
} void *
thr_fn(void *arg)
{
printids("new thread: ");
return((void *));
} int
main(void)
{
int err; err = pthread_create(&ntid, NULL, thr_fn, NULL);
if (err != )
err_exit(err, "can't create thread");
printids("main thread:");
sleep();
exit();
}

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

线程终止

如果进程中任意线程调用了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。

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

 #include "apue.h"
#include <pthread.h> void *
thr_fn1(void *arg)
{
printf("thread 1 returning\n");
return((void *));
} void *
thr_fn2(void *arg)
{
printf("thread 2 exiting\n");
pthread_exit((void *));
} int
main(void)
{
int err;
pthread_t tid1, tid2;
void *tret; err = pthread_create(&tid1, NULL, thr_fn1, NULL);
if (err != )
err_exit(err, "can't create thread 1");
err = pthread_create(&tid2, NULL, thr_fn2, NULL);
if (err != )
err_exit(err, "can't create thread 2");
err = pthread_join(tid1, &tret);
if (err != )
err_exit(err, "can't join with thread 1");
printf("thread 1 exit code %ld\n", (long)tret);
err = pthread_join(tid2, &tret);
if (err != )
err_exit(err, "can't join with thread 2");
printf("thread 2 exit code %ld\n", (long)tret);
exit();
}

线程可以通过调用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避免永久阻塞

 #include "apue.h"
#include <pthread.h> int
main(void)
{
int err;
struct timespec tout;
struct tm *tmp;
char buf[];
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&lock);
printf("mutex is locked\n");
clock_gettime(CLOCK_REALTIME, &tout);
tmp = localtime(&tout.tv_sec);
strftime(buf, sizeof(buf), "%r", tmp);
printf("current time is %s\n", buf);
tout.tv_sec += ; /* 10 seconds from now */
/* caution: this could lead to deadlock */
err = pthread_mutex_timedlock(&lock, &tout);
clock_gettime(CLOCK_REALTIME, &tout);
tmp = localtime(&tout.tv_sec);
strftime(buf, sizeof(buf), "%r", tmp);
printf("the time is now %s\n", buf);
if (err == )
printf("mutex locked again!\n");
else
printf("can't lock mutex again: %s\n", strerror(err));
exit();
}

这个程序对已有的互斥量加锁,演示了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函数则能唤醒等待该条件的所有线程。

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

 #include <pthread.h>

 struct msg {
struct msg *m_next;
/* ... more stuff here ... */
}; struct msg *workq; pthread_cond_t qready = PTHREAD_COND_INITIALIZER; pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER; void
process_msg(void)
{
struct msg *mp; for (;;) {
pthread_mutex_lock(&qlock);
while (workq == NULL)
pthread_cond_wait(&qready, &qlock);
mp = workq;
workq = mp->m_next;
pthread_mutex_unlock(&qlock);
/* now process the message mp */
}
} void
enqueue_msg(struct msg *mp)
{
pthread_mutex_lock(&qlock);
mp->m_next = workq;
workq = mp;
pthread_mutex_unlock(&qlock);
pthread_cond_signal(&qready);
}

自旋锁

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

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

自旋锁的接口与互斥量的接口类似,提供了以下的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的线程,就满足了屏障计数,所有的线程都被唤醒。

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

 #include "apue.h"
#include <pthread.h>
#include <limits.h>
#include <sys/time.h> #define NTHR 8 /* number of threads */
#define NUMNUM 8000000L /* number of numbers to sort */
#define TNUM (NUMNUM/NTHR) /* number to sort per thread */ long nums[NUMNUM];
long snums[NUMNUM]; pthread_barrier_t b; #ifdef SOLARIS
#define heapsort qsort
#else
extern int heapsort(void *, size_t, size_t,
int (*)(const void *, const void *));
#endif /*
* Compare two long integers (helper function for heapsort)
*/
int
complong(const void *arg1, const void *arg2)
{
long l1 = *(long *)arg1;
long l2 = *(long *)arg2; if (l1 == l2)
return ;
else if (l1 < l2)
return -;
else
return ;
} /*
* Worker thread to sort a portion of the set of numbers.
*/
void *
thr_fn(void *arg)
{
long idx = (long)arg; heapsort(&nums[idx], TNUM, sizeof(long), complong);
pthread_barrier_wait(&b); /*
* Go off and perform more work ...
*/
return((void *));
} /*
* Merge the results of the individual sorted ranges.
*/
void
merge()
{
long idx[NTHR];
long i, minidx, sidx, num; for (i = ; i < NTHR; i++)
idx[i] = i * TNUM;
for (sidx = ; sidx < NUMNUM; sidx++) {
num = LONG_MAX;
for (i = ; i < NTHR; i++) {
if ((idx[i] < (i+)*TNUM) && (nums[idx[i]] < num)) {
num = nums[idx[i]];
minidx = i;
}
}
snums[sidx] = nums[idx[minidx]];
idx[minidx]++;
}
} int
main()
{
unsigned long i;
struct timeval start, end;
long long startusec, endusec;
double elapsed;
int err;
pthread_t tid; /*
* Create the initial set of numbers to sort.
*/
srandom();
for (i = ; i < NUMNUM; i++)
nums[i] = random(); /*
* Create 8 threads to sort the numbers.
*/
gettimeofday(&start, NULL);
pthread_barrier_init(&b, NULL, NTHR+);
for (i = ; i < NTHR; i++) {
err = pthread_create(&tid, NULL, thr_fn, (void *)(i * TNUM));
if (err != )
err_exit(err, "can't create thread");
}
pthread_barrier_wait(&b);
merge();
gettimeofday(&end, NULL); /*
* Print the sorted list.
*/
startusec = start.tv_sec * + start.tv_usec;
endusec = end.tv_sec * + end.tv_usec;
elapsed = (double)(endusec - startusec) / 1000000.0;
printf("sort took %.4f seconds\n", elapsed);
for (i = ; i < NUMNUM; i++)
printf("%ld\n", snums[i]);
exit();
}

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

  

最新文章

  1. asp.net用户自定义控件传参
  2. JS-firstChild,firstElementChild,lastChild,firstElementChild,nextSibling,nextElementSibling
  3. django1.4日志模块配置及使用
  4. SQL存储过程生成顺序编码
  5. 一步步学敏捷开发:5. Scrum的4种会议
  6. linux下多ISP的策略路由
  7. c#类库中使用Session
  8. CXF Service Interceptor请求,响应报文之控制台输出
  9. Linux内核和驱动编译常见问题
  10. CentOS 7 多网卡绑定
  11. VMWare - Ubuntu 64 (16.04)之扩容介绍
  12. linux学习:特殊符号,数学运算,图像与数组与部分终端命令用法整理
  13. ubuntu16.04 pip install scrapy 报错处理
  14. 深入理解定位父级offsetParent及偏移大小offsetTop / offsetLeft / offsetHeight / offsetWidth
  15. maven 打包不同环境
  16. 安卓音、视频播放功能简单实现 --Android基础
  17. JFinal Web开发学习(八)后台集成H-ui-admin前端框架
  18. XE6 任务栏 控件
  19. 20172304 实验二 《Java面向对象程序设计》 实验报告
  20. ceph: health_warn clock skew detected on mon的解决办法

热门文章

  1. [Gym101138G][容斥原理]LCM-er
  2. [luogu3768] 简单的数学题 [杜教筛]
  3. [python]做一个简单爬虫
  4. Juice Junctions
  5. Educational Codeforces Round 8 B 找规律
  6. js 清空div
  7. 控制cxGrid 主从表的明细只展开一个
  8. spring rest 请求怎样添加Basic Auth请求頭
  9. 用 config drive 配置网络
  10. DataBinder.Eval值的判断