Linux Pthread 深入解析

 

Outline

- 1.线程特点

- 2.pthread创建

- 3.pthread终止

        - 4.mutex互斥量使用框架

        - 5.cond条件变量

        - 6.综合实例

================================================================================================

1. 线程特点

线程拥有自己独立的栈、调度优先级和策略、信号屏蔽字(创建时继承)、errno变量以及线程私有数据。进程的其他地址空间均被所有线程所共享,因此线程可以访问程序的全局变量和堆中分配的数据,并通过同步机制保证对数据访问的一致性。
 
2. pthread创建
pthread有一个线程ID,类型为pthread_t,在使用printf打印时,应转换为u类型。
pthread_equal可用于比较两个id是否相等;pthread_self用于获取当前线程的ID。
pthread_create用于创建新的线程,可以给线程传入一个void *类型的参数,例如一个结构体指针或者一个数值。
系统并不能保证哪个线程会现运行:新创建的线程还是调用线程。
 
3. pthread终止
a) 从线程函数中返回
b) 被同一进程中的其他线程取消
c) 线程调用pthread_exit
注意,线程的返回值需要转换为void *类型。
 
pthread_exit(void *ret)
pthread_join(pthread_t id, void **ret)
 
ret均可设置为NULL
 
4.  mutex 互斥量使用框架
pthread_mutex_t lock;
pthread_mutex_init 或者 PTHREAD_MUTEX_INITIALIZER(仅可用在静态变量)
pthread_mutex_lock / pthread_mutex_unlock / pthread_mutex_trylock
pthread_mutex_destroy
 
5. cond 条件变量
pthread_cond_t qready;
pthread_mutex_t qlock;
pthread_mutex_init 或者 PTHREAD_MUTEX_INITIALIZER
pthread_cond_init 或者 PTHREAD_COND_INITIALIZER
pthread_mutex_lock(&qlock...)
pthread_cond_wait(&qready, &qlock...) / pthread_cond_timewait
pthread_mutex_unlock(&qlock)
pthread_cond_destroy
 
//唤醒条件变量
pthread_cond_signal
pthread_cond_broadcast
 
条件变量是pthread中比较难以理解的一点,主要会产生以下疑惑:
Q1. 假如在调用pthread_{cond_wait | cond_timedwait}之前就调用pthread_cond_{signal | broadcast}会发生什么?
 
Q2. pthread_cond_{cond_wait | cond_timewait}为什么需要一个已经锁住的mutex作为变量?
 
Q3. pthread_cond_{signal | broadcast}使用之前必须获取wait中对应的mutex吗?
 
Q4. 假如pthread_cond_{signal | broadcast}必须获取mutex,那么下列两种形式,哪种正确?为什么?
 
 1)
 lock(lock_for_X);
 change(X);
 unlock(lock_for_X);
 pthread_cond_{signal | broadcast};
 
 2)
 lock(lock_for_X);
 change(X);
 pthread_cond_{signal | broadcast};
 unlock(lock_for_X);
 
----思考-------思考-------思考-------思考------思考-------思考------思考------思考-------思考-------
 
A1: 什么都不会发生,也不会出错,仅仅造成这次发送的signal丢失。
 
A2: 一般场景如下,我们需要检查某个条件是否满足(如队列X是否为空、布尔Y是否为真),假如没有条件变量,我们唯一的选择是
 
  1. while (1) {
  2. lock(lock_for_X);
  3. if (X is not empty) {
  4. unlock(lock_for_X);
  5. break;
  6. } else { //X is empty, loop continues
  7. unlock(lock_for_X);
  8. sleep(10);
  9. }
  10. }
  11. //X is not empty, loop ends
  12. process(X);
 
明显这种轮询的方式非常耗费CPU时间,这时候我们很容易的想到,如果有一种机制,可以异步通知我们队列的状态发生了变化,那么我们便无须再轮询,只要等到通知到来时再检查条件是否满足即可,其他时间则将程序休眠,因此现在代码变成这样:
 
  1. while (1) {
  2. lock(lock_for_X);
  3. if (X is not empty) {
  4. unlock(lock_for_X);
  5. break;
  6. } else {
  7. unlock(lock_for_X); //must called before my_wait(), otherwise no one can acquire the lock and make change to X
  8. -------------------------------------->窗口,由于已经解锁,其他程序可能改变X,并且试图唤醒mywait,但在一个繁忙的系统中,可能此时my_还没被调用!
  9. my_wait(); //go to sleep and wait for the notification
  10. }
  11. }
 
my_wait是一个假想的函数,作用如注释所示。
不难发现,这样做以后,我们无须再轮询了,只需要等待my_wait()被唤醒以后检查条件是否满足。
但 是请注意,正如图中所示,存在1个时间窗口。若其他程序在这个窗口中试图唤醒my_wait,由于此时my_wait还没有被调用,那么这个信号将丢失, 造成my_wait一直阻塞。解决的办法就是,要将unlock和my_wait合并成一个原子操作,这样就不会被其他程序插入执行。我想到这里,你应该 已经明白了,这个原子操作的函数就是pthread_cond_{signal | broadcast}.

A3: 是的。
 
A4: 对于1),在不同的操作系统中,可能会造成不确定的调度结果(可能会造成调度优先级反转);对于2)可以保证无论在何种操作系统中都将获得预期的调度顺序。
 
设想一个场景:有两个消费者线程A和B,我们设定A的优先级比B高,A正在等待条件变量被出发,即已经调用了pthread_wait,并且处于阻塞状态:
 
  1. lock(lock_for_X);
  2. while (X is empty) {
  3. pthread_cond_wait(&qready, &lock_for_X);
  4. }
  5. unlock(lock_for_X);
 
B中没有调用pthread_wait,而是做类似如下的处理:
 
  1. while(1) {
  2. lock(lock_for_X);
  3. dequeue(X);
  4. unlock(lock_for_X);
  5. }
另一个线程C,为生产者,采用1)方案,则代码如下,先unlock,再发出signal:
 
 lock(lock_for_X);
 change(X);
 unlock(lock_for_X);
 pthread_cond_{signal | broadcast};
 
当 发出unlock以后,发送signal之前,此时消费者B已经满足了运行条件,而消费者A虽然优先级比B高,但是由于其运行条件还需要signal,所 以不具备立刻运行的条件,此时就看操作系统如何实现调度算法了。有些操作系统,可能会因为A不具备立刻运行条件,即使它的优先级比B高,此时还是让B线程 先运行,那么,后续将分成两种情况:
 
(a) B获得了lock,但是还没有将X队列中的刚刚加入的条目移除,此时C调用了signal,A接收到了signal,由于A的优先级高,那么A抢占B,A 从函数pthread_cond_wait返回之前需要再次将lock上锁,但是A抢占后发现,lock被人锁住了(还没有被B释放),只好再次休眠,等 待锁被释放,结果B又被唤醒,也可能因此造成A和B的死锁,这个具体要看操作系统的调度算法。
 
(b) B获得了lock,并且执行了dequeue,然后释放了锁。此时C调用了signal,A接收到了signal,由于A的优先级高,那么A抢占B,A这 次顺利的获取了锁得以从pthread_cond_wait中返回,但是在检查条件时,却发现队列是空的,于是乎再次进入 pthread_cond_wait休眠。结果A又无法被执行,A可能由此进入饥饿状态。
 
但是如果C采用2)方案:
 
 lock(lock_for_X);
 change(X);
 pthread_cond_{signal | broadcast};
 unlock(lock_for_X);
 
在unlock以后,A、B都具备了立即运行的条件,由于A比B的优先级高,因此操作系统必定会先调度A执行,就避免了前面一种不确定的调度结果。
 
 
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h> static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; struct node
{
int n_number;
struct node *n_next;
} *head = NULL; /*[thread_func]*/ /*释放节点内存 */
static void cleanup_handler(void *arg)
{
printf("Cleanup handler of second thread.\n");
free(arg);
(void)pthread_mutex_unlock(&mtx);
} static void *thread_func(void *arg)
{
struct node *p = NULL;
pthread_cleanup_push(cleanup_handler, p); while ()
{
pthread_mutex_lock(&mtx);
//这个mutex_lock主要是用来保护wait等待临界时期的情况,
//当在wait为放入队列时,这时,已经存在Head条件等待激活
//的条件,此时可能会漏掉这种处理
//这个while要特别说明一下,单个pthread_cond_wait功能很完善,
//为何这里要有一个while (head == NULL)呢?因为pthread_cond_wait
//里的线程可能会被意外唤醒,如果这个时候head != NULL,
//则不是我们想要的情况。这个时候,
//应该让线程继续进入pthread_cond_wait while (head != NULL)
{
pthread_cond_wait(&cond, &mtx);
// pthread_cond_wait会先解除之前的pthread_mutex_lock锁定的mtx,
//然后阻塞在等待队列里休眠,直到再次被唤醒
//(大多数情况下是等待的条件成立而被唤醒,唤醒后,
//该进程会先锁定先pthread_mutex_lock(&mtx);,
// 再读取资源 用这个流程是比较清楚的
/*block-->unlock-->wait() return-->lock*/ p = head;
head = head->n_next;
printf("Got %d from front of queue\n", p->n_number);
free(p);
}
pthread_mutex_unlock(&mtx); //临界区数据操作完毕,释放互斥锁 } pthread_cleanup_pop();
return ;
} int main(void)
{
pthread_t tid;
int i;
struct node *p;
pthread_create(&tid, NULL, thread_func, NULL);
//子线程会一直等待资源,类似生产者和消费者,
//但是这里的消费者可以是多个消费者,
//而不仅仅支持普通的单个消费者,这个模型虽然简单,
//但是很强大
for (i = ; i < ; i++)
{
p = (struct node *)malloc(sizeof(struct node));
p->n_number = i;
pthread_mutex_lock(&mtx); //需要操作head这个临界资源,先加锁,
p->n_next = head;
head = p;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mtx); //解锁
sleep();
}
printf("thread 1 wanna end the cancel thread 2.\n");
pthread_cancel(tid);
//关于pthread_cancel,有一点额外的说明,它是从外部终止子线程,
//子线程会在最近的取消点,退出线程,而在我们的代码里,最近的
//取消点肯定就是pthread_cond_wait()了。
pthread_join(tid, NULL);
printf("All done -- exiting\n");
return ;
}
 
6. 综合实例
  1. /*
  2. * =====================================================================================
  3. *
  4. * Filename: pthread.c
  5. *
  6. * Description:
  7. *
  8. * Version: 1.0
  9. * Created: 08/17/11 11:06:35
  10. * Revision: none
  11. * Compiler: gcc
  12. *
  13. * Author: YOUR NAME (),
  14. * Company:
  15. *
  16. * =====================================================================================
  17. */
  18. #include <stdio.h>
  19. #include <pthread.h>
  20. #include <error.h>
  21. #include <stdlib.h>
  22. #include <unistd.h>
  23. #include <string.h>
  24. pthread_cond_t qready;
  25. pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;
  26. struct foo {
  27. int cnt;
  28. pthread_mutex_t f_lock;
  29. };
  30. void cleanup(void *arg)
  31. {
  32. printf("clean up: %s\n", (char *)arg);
  33. }
  34. void printids(char *str)
  35. {
  36. printf("%s pid = %u tid = %u / 0x%x\n",
  37. str, (unsigned int)getpid(), (unsigned int)pthread_self(), (unsigned int)pthread_self());
  38. }
  39. void *thread1(void *arg)
  40. {
  41. pthread_mutex_lock(&qlock);
  42. pthread_cond_wait(&qready, &qlock);
  43. pthread_mutex_unlock(&qlock);
  44. printids("thread1:");
  45. pthread_cleanup_push(cleanup, "thread 1 first cleanup handler");
  46. pthread_cleanup_push(cleanup, "thread 1 second cleanup handler");
  47. printf("thread 1 push complete!\n");
  48. pthread_mutex_lock(&((struct foo *)arg)->f_lock);
  49. ((struct foo *)arg)->cnt;
  50. printf("thread1: cnt = %d\n", ((struct foo *)arg)->cnt);
  51. pthread_mutex_unlock(&((struct foo *)arg)->f_lock);
  52. if (arg)
  53. return ((void *)0);
  54. pthread_cleanup_pop(0);
  55. pthread_cleanup_pop(0);
  56. pthread_exit((void *)1);
  57. }
  58. void *thread2(void *arg)
  59. {
  60. int exit_code = -1;
  61. printids("thread2:");
  62. printf("Now unlock thread1\n");
  63. pthread_mutex_lock(&qlock);
  64. pthread_mutex_unlock(&qlock);
  65. pthread_cond_signal(&qready);
  66. printf("Thread1 unlocked\n");
  67. pthread_cleanup_push(cleanup, "thread 2 first cleanup handler");
  68. pthread_cleanup_push(cleanup, "thread 2 second cleanup handler");
  69. printf("thread 2 push complete!\n");
  70. if (arg)
  71. pthread_exit((void *)exit_code);
  72. pthread_cleanup_pop(0);
  73. pthread_cleanup_pop(0);
  74. pthread_exit((void *)exit_code);
  75. }
  76. int main(int argc, char *argv[])
  77. {
  78. int ret;
  79. pthread_t tid1, tid2;
  80. void *retval;
  81. struct foo *fp;
  82. ret = pthread_cond_init(&qready, NULL);
  83. if (ret != 0) {
  84. printf("pthread_cond_init error: %s\n", strerror(ret));
  85. return -1;
  86. }
  87. if ((fp = malloc(sizeof(struct foo))) == NULL) {
  88. printf("malloc failed!\n");
  89. return -1;
  90. }
  91. if (pthread_mutex_init(&fp->f_lock, NULL) != 0) {
  92. free(fp);
  93. printf("init mutex failed!\n");
  94. }
  95. pthread_mutex_lock(&fp->f_lock);
  96. ret = pthread_create(&tid1, NULL, thread1, (void *)fp);
  97. if (ret != 0) {
  98. printf("main thread error: %s\n", strerror(ret));
  99. return -1;
  100. }
  101. ret = pthread_create(&tid2, NULL, thread2, (void *)1);
  102. if (ret != 0) {
  103. printf("main thread error: %s\n", strerror(ret));
  104. return -1;
  105. }
  106. ret = pthread_join(tid2, &retval);
  107. if (ret != 0) {
  108. printf("pthread join falied!\n");
  109. return -1;
  110. }
  111. else
  112. printf("thread2 exit code %d\n", (int)retval);
  113. fp->cnt = 1;
  114. printf("main thread: cnt = %d\n",fp->cnt);
  115. pthread_mutex_unlock(&fp->f_lock);
  116. sleep(1);    //there is no guarantee the main thread will run before the newly created thread, so we wait for a while
  117. printids("main thread:");
  118. printf("Press <RETURN> to exit\n");
  119. ret = pthread_cond_destroy(&qready);
  120. if (ret != 0) {
  121. printf("pthread_cond_destroy error: %s\n", strerror(ret));
  122. return -1;
  123. }
  124. getchar();
  125. return 0;
  126. }

Linux Pthread 深入解析(转-度娘818)的更多相关文章

  1. Linux下得到毫秒级时间--C语言实现(转-度娘818)

    Linux下得到毫秒级时间--C语言实现 原文链接: http://www.cnblogs.com/nwf5d/archive/2011/06/03/2071247.html #ifdef HAVE_ ...

  2. Android 2.3.5源码 更新至android 4.4,能够下载,度娘网盘

    Android 4.4源代码下载(linux合并) ==============================切割线结束========================= 旧版本号的能够使用115, ...

  3. 度娘果然毫无节操,纯粹就是order by 广告费 desc

    度娘果然毫无节操,纯粹就是order by 广告费 desc 必应搜索出来排第一,度娘根本就找不到在哪....

  4. linux mknod命令解析

    linux mknod命令解析 http://www.cnblogs.com/cobbliu/archive/2011/07/05/2389014.html mknod:make node  生成设备 ...

  5. Linux Command Line 解析

    Linux Command Line 解析 0 处理模型 Linux kernel的启动包括很多组件的初始化和相关配置,这些配置参数一般是通过command line进行配置的.在进行后续分析之前,先 ...

  6. Linux 网络配置文件解析

    Linux 网络配置文件解析 网络配置文件路径/etc/sysconfig/network-scripts/ifcfg-*     *代表网卡名 vim /etc/sysconfig/network- ...

  7. LINUX DNS客户端 解析域名慢的问题。

    Linux系统下域名解析的配置文件是/etc/resolv.conf cat /etc/resolv.conf # Generated by NetworkManager options single ...

  8. linux log日志解析

    linux log日志解析   其实,可以说成是监控系统的记录,系统一举一动基本会记录下来.这样由于信息非常全面很重要,通常只有 root 可以进行视察!通过登录文件(日志文件)可以根据屏幕上面的错误 ...

  9. Linux服务器配置DNS解析

    概述 DNS(Domain Name System,域名系统) DNS的作用,简单的说:就是把我们输入的网站域名翻译成IP地址的系统. 本文建立在已搭建好DNS服务器,这里讨论为linux机器配置DN ...

随机推荐

  1. 使用 VS2005 通过按钮自动上传文件到Linux

    首先去官网下载 winscp,官网地址:http://winscp.net/eng/download.php 因为我这里是做自动上传工具,所以我只下载了精简版的:Portable executable ...

  2. hihoCoder#1135

    刚开始学习C语言,准备在做hiho的题目的过程中来学习,在此进行记录,如果代码中有错误或者不当的地方还请指正. 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 The c ...

  3. python 中的高级函数map()

    map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回. 例如,对于list [1, 2 ...

  4. linux -a 到 -z 的意义

    shell if判断中常用的也就是绿色部分,尾部部分越看越不懂.从百度文库转载. [ -a FILE ] 如果 FILE 存在则为真. [ -b FILE ] 如果 FILE 存在且是一个块特殊文件则 ...

  5. C++引用的作用和用法

    引用就是某一变量(目标)的一个别名,对引用的操作与对变量直接操作完全一样. 引用的声明方法:类型标识符&引用名=目标变量名: 例如: int q; int &ra=a; 说明: &am ...

  6. C语言程序设计第四次作业

    态度决定一切,我依然要说这句话,每次同学们提交的作业,我都会认真评阅,相比实验课而言,可以有更充足的时间来发现问题,很多同学的代码依然会存在一些语法错误或者考虑不周全的现象,我提出了,那么,你认真看了 ...

  7. SQL排序

  8. Win8 安装 Scrapy

    安装Python2.7.11 32位(自带pip) 使用如下命令更新pip python -m pip install -U pip 下载lxml,建议32位,直接安装 https://pypi.py ...

  9. js 正则表达式 转至(七郎's Blog)

    //匹配帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线 var re =new RegExp("^[a-zA-Z][a-zA-Z0-9_]{5,19}$"); if( ...

  10. Velocity快速入门教程-脚本语法详解(转)

    1.变量 (1)变量的定义: #set($name = "hello")      说明:velocity中变量是弱类型的. 当使用#set 指令时,括在双引号中的字面字符串将解析 ...