Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2728512
  • 博文数量: 102
  • 博客积分: 1444
  • 博客等级: 中尉
  • 技术积分: 13891
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-29 10:58
文章分类

全部博文(102)

文章存档

2014年(29)

2013年(14)

2012年(59)

分类: LINUX

2012-05-27 22:38:14


一、线程的基本概念

    进程(process)和文件(files)是unix/linux操作系统两个最基本的抽象。进程是处于执行期的程序和它所包含的资源的总和,也就是说一个进程就是处于执行期的程序。一个线程(thread)就是运行在一个进程上下文中的一个逻辑流,不难看出,线程是进程中最基本的活动对象。
    
    在传统的系统中,一个进程只包含有一个线程。但在现代操作系统中,允许一个进程里面可以同时运行多个线程,这类程序就被称为多线程程序。所有的程序都有一个主线程(main thread),主线程是进程的控制流或执行线程。在多线程程序中,主线程可以创建一个或多个对等线程(peer  thread),从这个时间点开始,这些线程就开始并发执行。主线程和对等线程的区别仅在于主线程总是进程中的第一个运行的线程。从某种程度上看,线程可以看作是轻量级的进程。在linux操作系统中,内核调度的基本对象时线程,而不是进程,所以进程中的多个线程将由内核自动调度。

    每个线程都拥有独立的线程上下文(thread context),线程ID(thread ID,TID),程序计数器(pc),线程栈(stack)。其中,内核正是通过线程ID(TID)来识别线程,进行线程调度的。




二、线程与进程的异同点

A.相同点

<1> 比如都具有ID,一组寄存器,状态,优先级以及所要遵循的调度策略。
<2>每个进程都有一个进程控制块,线程也拥有一个线程控制块(在Linux内核,线程控制块与进程控制块用同一个结构体描述,即struct  task_struct),这个控制块包含线程的一些属性信息,操作系统使用这些属性信息来描述线程。
<3>线程和子进程的创建者可以在线程和子进程上实行某些控制,比如,创建者可以取消、挂起、继续和修改线程和子进程的优先级。

B.不同点
<1>主要区别:每个进程都拥有自己的地址空间,但线程没有自己独立的地址空间,而是运行在一个进程里的所有线程共享该进程的整个虚拟地址空间。
<2>线程的上下文切换时间开销比进程上下文切换时间开销要小的多
<3>线程的创建开销远远小于进程的创建
<4>子进程拥有父进程的地址空间和数据段的拷贝,因此当子进程修改它的变量和数据时,它不会影响父进程中的数据,但线程可以直接访问它进程中的数据段。
<5>进程之间通讯必须使用进程间通讯机制,但线程可以与进程中的其他线程直接通讯
<6>线程可以对同一进程中的其他线程实施大量控制,但进程只能对子进程实施控制
<7>改变主线程的属性可能影响进程中其他的线程,但对父进程的修改不影响子进程


三、线程相关的API

A.线程的创建



参数说明:

thread:指向pthread_t类型的指针,该地址将存放线程创建成功之后的线程TID。
attr:用户设置线程的属性,一般都不需要特殊设置,所以可简单设置为NULL。
*(*start_routine)(void *):传递新线程所要执行的函数的地址。
arg:新线程所有执行的函数的参数。

调用成功,则返回值是0,如果失败则返回错误代码。

注意:我们可以看到,如果想启动一个线程,就必须让这个线程关联一个子函数。我们一般称此函数为线程函数,但是我们又发现,在我们给线程函数传参数时,标准线程创建接口只留了 一个参数传递。思考?如果想给线程函数传递多个参数,该怎么解决呢?

B.线程终止



参数说明 :
value_ptr指向线程放回的某个对象

线程通过调用pthread_exit函数终止执行,并带回指向某个对象的指针。

注意:绝不能用它返回一个指向局部变量的指针,因为线程调用该函数后,这个局部变量就不存在了,这将引起严重的程序漏洞。

C.等待线程终止



一般此函数用在主线程中,等待通过thread指定的线程终止,此函数调用成功,可以通过value_ptr获取终止线程的返回值。

注意:如果等待的线程没有终止,此函数将引起调用者阻塞。成功返回0,失败返回-1。 

D.线程取消




如果想取消一个正在运行的线程,可以调用此函数。

参数说明:
thread:要取消的线程

函数返回值:成功返回0,失败返回-1

案例探究:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #include <string.h>

  5. char buf[] = "Hello word";

  6. void *pthread_function1(void *arg)
  7. {
  8.     while(1)
  9.     {
  10.         sleep(2);
  11.         printf("pthread_function : %s.\n",buf);
  12.     }
  13. }

  14. void *pthread_function2(void *arg)
  15. {
  16.     int i = 0;

  17.     for(i = 0;i < strlen(buf);i ++)
  18.     {
  19.         *(int *)arg += 1;
  20.         sleep(1);
  21.     }

  22.     pthread_exit("pthread_function2 over");
  23. }

  24. int main()
  25. {
  26.     pthread_t tid1,tid2;
  27.     int    count = 0;
  28.     void *value_ptr;
  29.     
  30.     if(pthread_create(&tid1,NULL,pthread_function1,NULL) != 0)
  31.     {
  32.         perror("Fail to pthread create");
  33.         return -1;
  34.     }else{
  35.         printf("create pthread %lu.\n",tid1);
  36.     }

  37.     if(pthread_create(&tid2,NULL,pthread_function2,(void *)&count) != 0)
  38.     {
  39.         perror("Fail to pthread create");
  40.         exit(EXIT_FAILURE);
  41.     }else{
  42.         printf("create pthread %lu.\n",tid2);
  43.     }
  44.     
  45.     if(pthread_join(tid2,&value_ptr) < 0)
  46.     {
  47.         perror("Fail to pthread_join");
  48.         exit(EXIT_FAILURE);
  49.     }
  50.     
  51.     printf("pthread %lu join success,return string : %s.\n",tid1,(char *)value_ptr);

  52.     if((pthread_cancel(tid1)) < 0)
  53.     {
  54.         perror("Fail to pthread cancel");
  55.         exit(EXIT_FAILURE);
  56.     }
  57.     
  58.     printf("pthread %lu cancel success.\n",tid2);
  59.     printf("main pthread sleeping...\n");
  60.     sleep(5);
  61.     
  62.     return 0;
  63. }

在主线程中,创建了两个子线程tid1,tid2。
tid1线程每隔2秒钟打印一次全局数组buf的内容。
tid2线程没1秒统计一下buf数组中的字符,统计结束后调用pthread_exit退出。

运行结果如下:



可以看出,在调用pthread_cancel后,对应的线程就取消了。

案例二

有一buf[] = "hello word.\n";
创建两个线程A、B;

A线程将buf的内容向文件 test写5此;
B线程读取test文件五次,将读取的内容在终端上进行打印

  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <errno.h>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include <fcntl.h>

  9. #define MAX 50

  10. char buf[] = "hello word.\n";

  11. void *write_file(void *file_name)
  12. {
  13.     int fd;
  14.     int i = 0;

  15.     if((fd = open((char *)file_name,O_CREAT | O_TRUNC | O_APPEND | O_WRONLY,0666)) < 0)
  16.     {
  17.         fprintf(stderr,"Fail to open %s : %s.\n",(char *)file_name,strerror(errno));
  18.         pthread_exit(NULL);
  19.     }
  20.     
  21.     for(i = 0;i < 5;i ++)
  22.     {
  23.         write(fd,buf,strlen(buf));
  24.     }

  25.     pthread_exit(NULL);
  26. }

  27. void *read_file(void *file_name)
  28. {
  29.     int fd;
  30.     int n = 0,i = 0;
  31.     char buf[MAX];

  32.     if((fd = open((char *)file_name,O_CREAT | O_RDONLY,0666)) < 0)
  33.     {
  34.         fprintf(stderr,"Fail to open %s : %s.\n",(char *)file_name,strerror(errno));
  35.         pthread_exit(NULL);
  36.     }

  37.     for(i = 0;i < 5;i ++)
  38.     {
  39.         n = read(fd,buf,sizeof(buf));
  40.         buf[n] = '\0';
  41.         printf("read %d : %s\n",n,buf);
  42.     }

  43.     pthread_exit(NULL);
  44. }

  45. int main(int argc,char *argv[])
  46. {
  47.     int res;
  48.     pthread_t tid1,tid2;
  49.     void *arg = argv[1];
  50.     
  51.     if(argc < 2)
  52.     {
  53.         fprintf(stderr,"usage : %s argv[1].\n",argv[0]);
  54.         return -1;
  55.     }
  56.     
  57.     res = pthread_create(&tid1,NULL,write_file,arg);
  58.     if(res != 0)
  59.     {
  60.         perror("Fail to pthread create");
  61.         exit(EXIT_FAILURE);
  62.     }

  63.     res = pthread_create(&tid2,NULL,read_file,arg);
  64.     if(res != 0)
  65.     {
  66.         perror("Fail to pthread create");
  67.         exit(EXIT_FAILURE);
  68.     }

  69.     pthread_join(tid1,NULL);
  70.     pthread_join(tid2,NULL);

  71.     exit(EXIT_SUCCESS);
  72. }
运行结果如下:



什么玩意?和我猜想的结果不一样呀。思考?为什么是这种情况。

我们更希望,在A线程写完后,B线程读。B线程读完后,A线程在写。想要达到这种效果,我们可以通过线程的同步和互斥。

四、线程的同步

A.线程间机制

<1>多线程共享同一个进程的地址空间
<2>有点:线程间很容易进行通信,通过全局变量实现数据共享和交换
<3>缺点:多个线程同时访问共享对象时需要引入同步和互斥机制

B.线程间同步 - P/V操作

<1>信号量代表某一类资源,其值表示系统中该资源的数量

<2>信号量是 一个受保护的变量,只能通过三种操作来访问

a.初始化

b.P操作(申请资源)

c.v操作(释放资源)

<3>信号量的值为非负整数,其值为0时,表示当前系统中无此类资源

P(s)含义如下:

if(信号量的值大于0)
{
    申请资源的任务继续运行;
    信号量的值减一;

}else{

    申请资源的任务阻塞;
}

V(s)含义如下:

if(没有任务在等待该资源)
{
    信号量的值加一;
}else{
    唤醒第一个等待的任务,让其继续运行;
}

注意:一个任务申请资源时有可能被阻塞,一个任务释放资源时一定不会被阻塞

C.posix中定义了两类信号量

<1>无名信号量(基于内存的信号量)
<2>有名信号量(Linux只实现了无名信号量)

D.pthread库中常用的信号量操作函数

<1>信号量初始化



sem_init()初始化一个定位在sem的匿名信号量。value参数指定信号量的初始值。pshared参数指明信号量是由进程内线程共享,还是由进程之间共享。如果pshared的值为0,那么信号量将被进程内的线程共享,并且应该设置在所有线程都可以看见的地址上(如全局变量,或者堆上动态分配的变量)。

如果pshared是非零值,那么信号量将在进程之间共享,并且应该定位共享内存区域。因为fork()创建的孩子继承其父亲的内存映射,因此它也可以见到这个信号量。所有可以访问共享内存区域的进程都可以用sem_post、sem_wait操作信号量。

参数说明:

sem :信号量对象

pshared:控制信号量的类型,0表示这个信号量时当前进程的局部信号量,否则,这个信号量就可以在多个进程间共享。

value:信号量的初始值(即资源的个数);

<2>p操作,即申请资源



sem_wait的作用是以原子操作的方式给信号量的值减1,但它会等到信号量非0时才会开始减法操作。如果此时信号量的值为0,这个函数就会等待,直到有线程增加了该信号量的值使其不再为0。

<2>V操作,即释放资源



sem_post的作用是以原子操作的方式给信号量的值加1。

<3>信号量销毁



这个函数的作用是,用完信号量后对它进行清理,清理该信号量所拥有的资源。

案例三、一个线程输入,两个线程读(读完清除buf的内容),实现同步操作

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <errno.h>
  5. #include <pthread.h>
  6. #include <semaphore.h>

  7. #define MAX 100
  8. #define N 2

  9. char share_buf[MAX];

  10. sem_t rsem,wsem;

  11. void* read_share_buf(void *arg)
  12. {
  13.     int num = *((int *)arg);
  14.     
  15.     printf("Create pthread %d success.\n",*((int *)arg));

  16.     while(1)
  17.     {
  18.         if(sem_wait(&rsem) < 0)
  19.         {
  20.             fprintf(stderr,"%d fail to sem wait : %s.\n",num,strerror(errno));
  21.             pthread_exit(NULL);
  22.         }
  23.     
  24.         printf("pthread %d read buf : %s.\n",num,share_buf);
  25.         memset(share_buf,0,sizeof(share_buf));

  26.         if(sem_post(&wsem) < 0)
  27.         {
  28.             fprintf(stderr,"%d fail to sem post : %s.\n",num,strerror(errno));
  29.             pthread_exit(NULL);
  30.         }
  31.     }

  32. }

  33. int do_work()
  34. {

  35.     while(1)
  36.     {
  37.         if(sem_wait(&wsem) < 0)
  38.         {
  39.             perror("Fail to sem wait");
  40.             exit(EXIT_FAILURE);
  41.         }
  42.         
  43.         printf(">");
  44.         fgets(share_buf,MAX,stdin);
  45.         share_buf[strlen(share_buf) - 1] = '\0';
  46.         
  47.         if(strncmp(share_buf,"quit",4) == 0)
  48.         {
  49.             break;
  50.         }

  51.         if(sem_post(&rsem) < 0)
  52.         {
  53.             perror("Fail to sem post");
  54.             exit(EXIT_FAILURE);
  55.         }
  56.     }

  57.     return 0;
  58. }

  59. int main()
  60. {
  61.     int res,i;
  62.     pthread_t tid[N];

  63.     if(sem_init(&rsem,0,0) < 0)
  64.     {
  65.         perror("Fail to sem_init");
  66.         exit(EXIT_FAILURE);
  67.     }

  68.     if(sem_init(&wsem,0,1) < 0)
  69.     {
  70.         perror("Fail to sem_init");
  71.         exit(EXIT_FAILURE);
  72.     }
  73.     
  74.     for(i = 0;i < N;i ++)
  75.     {
  76.         res = pthread_create(&tid[i],NULL,read_share_buf,(void *)&i);
  77.         usleep(500);
  78.         if(res != 0)
  79.         {
  80.             perror("Fail to create pthread");
  81.             exit(EXIT_FAILURE);
  82.         }
  83.     }

  84.     do_work();

  85.     for(i = 0;i < N;i ++)
  86.     {
  87.         pthread_cancel(tid[i]);
  88.     }

  89.     if(sem_destroy(&rsem) < 0)
  90.     {
  91.         perror("Fail to sem destroy rsem");
  92.         exit(EXIT_FAILURE);
  93.     }

  94.     if(sem_destroy(&wsem) < 0)
  95.     {
  96.         perror("Fail to sem destroy wsem");
  97.         exit(EXIT_FAILURE);
  98.     }

  99.     exit(EXIT_SUCCESS);
  100. }
运行结果如下:



五、线程的互斥锁

<1>引入互斥(mutual exclusion)锁的目的是用来保证共享数据操作的完整性。
<2>互斥锁主要用来保护临界资源。
<3>每个临界资源都由一个互斥锁来保护,任何时刻最多只能有一个线程能访问该资源。
<4>线程必须先获得互斥锁才能访问临界资源,访问完临界资源后释放该锁。如果无法获得锁,线程会阻塞直到获得锁为止。

A、锁的初始化



当我们定义一个锁时我们应当对它初始化。

a.静态初始化可以通过PTHREAD_MUTEX_INITIALIZER宏
b.动态初始化可以通过pthread_mutex_init函数进行,一般在通过pthread_mutex_init初始化的锁,在不需要时应调用pthread_mutex_destroy销毁。

B.获得互斥锁和释放互斥锁



a.我们可以通过pthread_mutex_lock来获得锁

注意: 如果想获得的锁已经被别的线程获取了,此时pthread_mutex_lock将引起调用者阻塞

pthread_mutex_trylock我们称尝试获得锁,如果不能获得锁,它不会引起调用者阻塞而是立即放回。

b.我们可以通过pthread_mutex_unlock来释放获得的锁

案例四、通过互斥锁对文件进行读写操作,一个线程读,一个线程写。

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <errno.h>
  5. #include <pthread.h>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include <fcntl.h>

  9. #define MAX 100

  10. pthread_mutex_t rwlock = PTHREAD_MUTEX_INITIALIZER;

  11. void *read_file(void *arg)
  12. {    
  13.     int fd;
  14.     int n;
  15.     char buf[MAX];

  16.     if((fd = open((char *)arg,O_RDONLY | O_CREAT,0666)) < 0)
  17.     {
  18.         fprintf(stderr,"Fail to open %s : %s.\n",(char *)arg,strerror(errno));
  19.         pthread_exit(NULL);
  20.     }

  21.     while(1)
  22.     {
  23.         if(pthread_mutex_lock(&rwlock) < 0)
  24.         {
  25.             perror("Fail to pthread mutex lock");
  26.             pthread_exit(NULL);
  27.         }
  28.         
  29.         n = read(fd,buf,MAX);
  30.         buf[n] = '\0';

  31.         printf("Read %d character : %s.\n",n,buf);

  32.         if(strncmp(buf,"quit",4) == 0)
  33.         {
  34.             if(pthread_mutex_unlock(&rwlock) < 0)
  35.             {
  36.                 perror("Fail to pthread mutex unlock");
  37.                 pthread_exit(NULL);
  38.             }

  39.             break;
  40.         }

  41.         if(pthread_mutex_unlock(&rwlock) < 0)
  42.         {
  43.             perror("Fail to pthread mutex unlock");
  44.             pthread_exit(NULL);
  45.         }

  46.         sleep(1);
  47.     }

  48.     close(fd);
  49.     pthread_exit(NULL);
  50. }

  51. void *write_file(void *arg)
  52. {
  53.     int fd;
  54.     char buf[MAX];
  55.     
  56.     if((fd = open((char *)arg,O_CREAT | O_TRUNC | O_WRONLY)) < 0)
  57.     {
  58.         fprintf(stderr,"Fail to open %s : %s.\n",(char *)arg,strerror(errno));
  59.         pthread_exit(NULL);
  60.     }

  61.     while(1)
  62.     {    
  63.         printf(">");
  64.         if(pthread_mutex_lock(&rwlock) < 0)
  65.         {
  66.             perror("Fail to pthread mutex lock");
  67.             pthread_exit(NULL);
  68.         }
  69.         
  70.         fgets(buf,sizeof(buf),stdin);
  71.         buf[strlen(buf)-1] = '\0';
  72.         write(fd,buf,strlen(buf));
  73.         
  74.         if(strncmp(buf,"quit",4) == 0)
  75.         {
  76.             if(pthread_mutex_unlock(&rwlock) < 0)
  77.             {
  78.                 perror("Fail to pthread mutex unlock");
  79.                 pthread_exit(NULL);
  80.             }

  81.             break;
  82.         }
  83.             
  84.         if(pthread_mutex_unlock(&rwlock) < 0)
  85.         {
  86.             perror("Fail to pthread mutex unlock");
  87.             pthread_exit(NULL);
  88.         }

  89.         sleep(1);
  90.     }
  91.     
  92.     close(fd);
  93.     pthread_exit(NULL);
  94. }

  95. int main(int argc,char *argv[])
  96. {
  97.     pthread_t rtid,wtid;
  98.     int res;

  99.     if(argc < 2)
  100.     {
  101.         fprintf(stderr,"usage : %s argv[1].\n",argv[0]);
  102.         exit(EXIT_FAILURE);
  103.     }

  104.     res = pthread_create(&rtid,NULL,read_file,(void *)argv[1]);
  105.     if(res != 0){
  106.         perror("Fail to create pthread");
  107.         exit(EXIT_FAILURE);
  108.     }

  109.     res = pthread_create(&wtid,NULL,write_file,(void *)argv[1]);
  110.     if(res != 0){
  111.         perror("Fail to create pthread");
  112.         exit(EXIT_FAILURE);
  113.     }
  114.         
  115.     pthread_join(wtid,NULL);
  116.     pthread_join(rtid,NULL);

  117.     exit(EXIT_SUCCESS);
  118. }
运行结果如下:



上面的代码,读线程和写线程每次操作完之后都用了一下sleep(1),如果不这样做想想后果会则样?

其实我们更希望,当读线程发现文件中并没有数据后,就进行阻塞.当写线程写完数据之后就去通知读线程进行读操作。
要想实现这种异步通知的方法,我们就可以通过线程的条件变量来实现。

六、线程的条件变量

A.条件变量定义及初始化



和线程的互斥锁一样,我们也有两种方式初始化条件变量;

a.静态初始化:可以通过PTHREAD_COND_INITIALIZER初始化。

b.动态初始化:可以通过pthread_cond_init进行,如果不需要在使用此条件变量,也应该调用pthread_cond_destroy销毁

B.等待条件变量



参数说明:

第一个参数是等待的条件变量,第二个参数在是线程互斥锁。

pthread_cond_wait函数使用时一般都和互斥锁一起用,他们一起完成线程的同步。

注意:pthread_cond_wait函数一上来会判断等待的条件是否满足,如果不满足将引起调用的线程阻塞,直到条件满足。需要注意的时,pthread_cond_wait函数在阻塞前会释放互斥锁,这就要求在调用它之前应先获取互斥锁
(何时条件满足?当有线程调用pthread_cond_signal或pthread_cond_broadcase时,等待的条件满足,此时pthread_cond_wait函数将返回,返回时它将重新获取互斥锁)

C.唤醒等待条件变量的线程



pthread_cond_broadcase函数唤醒所有等待条件变量的线程。
pthread_cond_signal函数唤醒所有等待条件变量线程中的一个线程,一般唤醒的是第一个等待条件变量的线程。

案例5.异步通知读写

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <errno.h>
  5. #include <pthread.h>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include <fcntl.h>

  9. #define MAX 100

  10. pthread_mutex_t rwlock = PTHREAD_MUTEX_INITIALIZER;
  11. pthread_cond_t     rwcond = PTHREAD_COND_INITIALIZER;

  12. void *read_file(void *arg)
  13. {    
  14.     int fd;
  15.     int n;
  16.     char buf[MAX];

  17.     if((fd = open((char *)arg,O_RDONLY | O_CREAT | O_TRUNC,0666)) < 0)
  18.     {
  19.         fprintf(stderr,"Fail to open %s : %s.\n",(char *)arg,strerror(errno));
  20.         pthread_exit(NULL);
  21.     }

  22.     while(1)
  23.     {
  24.         if(pthread_mutex_lock(&rwlock) < 0)
  25.         {
  26.             perror("Fail to pthread mutex lock");
  27.             pthread_exit(NULL);
  28.         }
  29.         
  30.         while((n = read(fd,buf,MAX)) == 0)
  31.         {
  32.             if(pthread_cond_wait(&rwcond,&rwlock) < 0)
  33.             {
  34.                 perror("Fail to pthread cond wait");
  35.                 pthread_exit(NULL);
  36.             }
  37.         }

  38.         buf[n] = '\0';

  39.         printf("Read %d character : %s.\n",n,buf);

  40.         if(strncmp(buf,"quit",4) == 0)
  41.         {
  42.             if(pthread_mutex_unlock(&rwlock) < 0)
  43.             {
  44.                 perror("Fail to pthread mutex unlock");
  45.                 pthread_exit(NULL);
  46.             }

  47.             break;
  48.         }

  49.         if(pthread_mutex_unlock(&rwlock) < 0)
  50.         {
  51.             perror("Fail to pthread mutex unlock");
  52.             pthread_exit(NULL);
  53.         }

  54.     }

  55.     close(fd);
  56.     pthread_exit(NULL);
  57. }

  58. void *write_file(void *arg)
  59. {
  60.     int fd;
  61.     char buf[MAX];
  62.     
  63.     if((fd = open((char *)arg,O_CREAT | O_TRUNC | O_WRONLY,0666)) < 0)
  64.     {
  65.         fprintf(stderr,"Fail to open %s : %s.\n",(char *)arg,strerror(errno));
  66.         pthread_exit(NULL);
  67.     }

  68.     while(1)
  69.     {    
  70.         if(pthread_mutex_lock(&rwlock) < 0)
  71.         {
  72.             perror("Fail to pthread mutex lock");
  73.             pthread_exit(NULL);
  74.         }
  75.         
  76.         printf(">");
  77.         fgets(buf,sizeof(buf),stdin);
  78.         buf[strlen(buf)-1] = '\0';
  79.         write(fd,buf,strlen(buf));
  80.             
  81.         if(strncmp(buf,"quit",4) == 0)
  82.         {
  83.             if(pthread_mutex_unlock(&rwlock) < 0)
  84.             {
  85.                 perror("Fail to pthread mutex unlock");
  86.                 pthread_exit(NULL);
  87.             }

  88.             if(pthread_cond_signal(&rwcond) < 0)
  89.             {
  90.                 perror("Fail to cond signal");
  91.                 pthread_exit(NULL);
  92.             }

  93.             usleep(500);

  94.             break;
  95.         }

  96.         if(pthread_mutex_unlock(&rwlock) < 0)
  97.         {
  98.             perror("Fail to pthread mutex unlock");
  99.             pthread_exit(NULL);
  100.         }

  101.         if(pthread_cond_signal(&rwcond) < 0)
  102.         {
  103.             perror("Fail to cond signal");
  104.             pthread_exit(NULL);
  105.         }

  106.         usleep(500);
  107.     }
  108.     
  109.     close(fd);
  110.     pthread_exit(NULL);
  111. }

  112. int main(int argc,char *argv[])
  113. {
  114.     pthread_t rtid,wtid;
  115.     int res;

  116.     if(argc < 2)
  117.     {
  118.         fprintf(stderr,"usage : %s argv[1].\n",argv[0]);
  119.         exit(EXIT_FAILURE);
  120.     }

  121.     res = pthread_create(&rtid,NULL,read_file,(void *)argv[1]);
  122.     if(res != 0){
  123.         perror("Fail to create pthread");
  124.         exit(EXIT_FAILURE);
  125.     }
  126.     
  127.     usleep(500);

  128.     res = pthread_create(&wtid,NULL,write_file,(void *)argv[1]);
  129.     if(res != 0){
  130.         perror("Fail to create pthread");
  131.         exit(EXIT_FAILURE);
  132.     }
  133.         
  134.     pthread_join(wtid,NULL);
  135.     pthread_join(rtid,NULL);

  136.     exit(EXIT_SUCCESS);
  137. }
运行结果:



注意:pthread_cond_signal要加上少量的延迟,因为内核需要时间通知等待条件变量的线程,pthread_cond_wait返回时需要重新获取锁,也需要时间。


















阅读(12940) | 评论(7) | 转发(29) |
给主人留下些什么吧!~~

JuStin_Lo2021-01-03 01:18:43

草根老师:它是一个条件等待函数,调用这个函数就会让线程阻塞。上面有个read函数,返回0的时候,表示还没有数据可读,那就让线程等待呗。当一个线程写了数据时,它就会调用pthread_cond_signal函数唤醒等待的线程哦

写得很棒!!感谢老师!!

回复 | 举报

kongyu682015-07-21 10:13:22

老师,好热心奥!

草根老师2014-07-13 17:21:43

xusigeng01:你好,案例5的37行pthread_cond_wait(&rwcond,&rwlock),怎么判断条件满不满足的?

它是一个条件等待函数,调用这个函数就会让线程阻塞。上面有个read函数,返回0的时候,表示还没有数据可读,那就让线程等待呗。当一个线程写了数据时,它就会调用pthread_cond_signal函数唤醒等待的线程哦

回复 | 举报

xusigeng012014-07-12 17:27:12

你好,案例5的37行pthread_cond_wait(&rwcond,&rwlock),怎么判断条件满不满足的?

zhangkaijia4032013-10-07 23:26:44

草根老师:文件中没有数据,read的时候不会阻塞呀,直接返回0了哦

哦,我搞错了,例程四的读线程是阻塞在第28行pthread_mutex_lock(&rwlock);函数上,
我原以为是阻塞在34行的n = read(fd,buf,MAX);函数上,所以把例程5也搞错了。

学习到很多知识,谢谢分享!

回复 | 举报