• posix thread 浅谈


    用Posix thread进行多线程设计,就不怕跨平台了,因为很多OS都兼容Posix thread,如Linux/Windows等,甚至嵌入式系统上(如rt-thread)都支持posix thread API。线程有比进程体积小,速率高,速度快等优势。所以编程时,如果涉及到效率和速度时,采用pthread_create()一个线程总比 fork()一个进程好些。

    Posxi thread 线程操作主要有创建(creation),终止(termination),同步(joins,blocking),调度(scheduling),数据管理(datamanagement)和交互(interaction).


    可以从以下线程框图了解线程的构架:

     

    多线程间关系:


    多线程间共享内存模型:

    与普通的fork()进程不一样,线程很简单,线程并不需要维护线程列表,也不需要知道谁创建了它。以下是pthread_create()与fork()在各种平台上,性能的比较:

    • The primary motivation for using Pthreads is to realize potential program performance gains.
    • When compared to the cost of creating and managing a process, a thread can be created with much less operating system overhead. Managing threads requires fewer system resources than managing processes.

    For example, the following table compares timingresults for the fork() subroutineand the pthread_create() subroutine.Timings reflect 50,000 process/thread creations, were performed with the time utility, and units are in seconds, nooptimization flags.

    Note: don't expect the sytem and user times toadd up to real time, because these are SMP systems with multiple CPUs workingon the problem at the same time. At best, these are approximations run on localmachines, past and present.

    Platform

    fork()

    pthread_create()

    real

    user

    sys

    real

    user

    sys

    Intel 2.8 GHz Xeon 5660 (12cpus/node)

    4.4

    0.4

    4.3

    0.7

    0.2

    0.5

    AMD 2.3 GHz Opteron (16cpus/node)

    12.5

    1.0

    12.5

    1.2

    0.2

    1.3

    AMD 2.4 GHz Opteron (8cpus/node)

    17.6

    2.2

    15.7

    1.4

    0.3

    1.3

    IBM 4.0 GHz POWER6 (8cpus/node)

    9.5

    0.6

    8.8

    1.6

    0.1

    0.4

    IBM 1.9 GHz POWER5 p5-575 (8cpus/node)

    64.2

    30.7

    27.6

    1.7

    0.6

    1.1

    IBM 1.5 GHz POWER4 (8cpus/node)

    104.5

    48.6

    47.2

    2.1

    1.0

    1.5

    INTEL 2.4 GHz Xeon (2 cpus/node)

    54.9

    1.5

    20.8

    1.6

    0.7

    0.9

    INTEL 1.4 GHz Itanium2 (4 cpus/node)

    54.5

    1.1

    22.2

    2.0

    1.2

    0.6

    在同一个线程或进程中所创建的线程共同享有一样的地址空间。

    线程间共享:

    .进程指令(process instructions)

    .大部分数据(most data)

    .文件(descriptors)

    .信号和信号句柄(signals and signal handlers)

    .当前工作目录(current working directory)

    .用户和组id(user and group id)

    线程独自属性:

    .线程id(thread id)

    .寄存器(内容)和栈不同(set of registers,stack pointer)

    .局部变量,返回地址(stack for local variables,return addresses)

    .信号mask(signal mask)

    .优先级(priority)

    .返回值(return value errno)

    主要的操作函数:

    /*创建一个线程,成功返回0,失败返回error错误标志*/

    1. int pthread_create(pthread_t * thread,            //thread :线程id, unsigned long intxi型  
    2.                     const pthread_attr_t *attr,       //attr: 线程属性参数,创建时将根据这个参数进行线程初始化  
    3.                     void *(*start_routine)(void *), //start_routine:指向线程所调用的函数  
    4.                     void *arg);                                //arg :线程传递参数   

    /* 终止线程,成功返回0,失败返回error错误 标志*/

    1. void pthread_exit(void *retval);      //retval:返回值指针  

      /*等待直到id为th线程运行结束(合并一个线程的意思)*/

    1. int pthread_join(pthread_t th, void**thread_return);  // th:线程id  
    2.                                         // thread_return :线程终止或取消时的返回值指针  

    /*获取当前线程id*/

    1. pthread_t pthread_self(void);   

    线程的同步机制:

    .互斥量(mutexes)

    .连接/合并(joins)

    .条件变量(condition variables)


    /*线程间互斥量操作函数,顾名思义*/

    1. int pthread_mutex_lock(pthread_mutex_t*mutex);//获取mutex,成功返0,失败返回错误标志,并阻塞当前线程  
    2. intpthread_mutex_trylock(pthread_mutex_t *mutex); //同上,不同的是多了个try(也就是说先try一下)  
    3. //如果在当前线程中,如果同一个互斥量已经被当前线程锁住,pthread_mutex_tyrlock将立即返回(成功).如果互斥量类型为:PTHREAD_MUTEX_RECURSIVE那么mutexlock count将自加一,然后立即返回(成功)  
    4. int pthread_mutex_unlock(pthread_mutex_t*mutex);   //释放一个mutex  

    实现原理:互斥量用于多线程对临界资源的访问,通过mutex lock count来判定是否锁住,初始值为0,当pthread_mutex_lock时mutex lock_count 自加,pthread_mutex_unlock时将mutex_lock_count自减。所以互斥量可用时mutex_lock_count = 0,对于一个临界资源,使用前应先lock,使用完后再unlock,如果使用不当,会有意外发生,但如果先unlock那么 mutex_lock_count 自减1,说明改互斥量将可以同时使用2次了。

    条件变量操作函数:

    /*初始化一个条件变量cond(布尔型),成功返回0,失败返回error错误标志*/

    1. int pthread_cond_init(pthread_cond_t *restrictcond,     
    2.              const pthread_condattr_t*restrict attr);  

    /*销毁一个条件变量cond,成功返回0,失败返回error错误标志*/

    1. int pthread_cond_destroy(pthread_cond_t*cond);  

    /*释放一个互斥量且等待(即阻塞当前线程)一个条件变量cond为真,后再lock*/ 

      1. <pre name="code" class="cpp"> int pthread_cond_timedwait(pthread_cond_t*restrict cond, pthread_mutex_t *restrict mutex,  
      2.  const struct timespec *restrictabstime);//等待条件变量cond是否为真,时限为abstime  
      3.  int pthread_cond_wait(pthread_cond_t*restrict cond,  
      4.  pthread_mutex_t *restrict mutex); //等待条件cond是否为真,时限为cond真为止</pre>  
      5. <pre></pre>  
      6. <p></p>  
      7. <p>/*释放条件变量cond,唤醒先前已被阻塞的线程*/ </p>  
      8. <p></p>  
      9. <pre name="code" class="cpp"> intpthread_cond_broadcast(pthread_cond_t *cond);//唤醒所有因条件变量cond而阻塞的线程  
      10.  intpthread_cond_signal(pthread_cond_t *cond);// 唤醒一个因条件变量cond而阻塞的线程</pre><pre name="code" class="cpp"><p& gt;<span style="font-size:10px;"></span></p></pre>  
      11. <p></p>  
      12. <p>编程实例:</p>  
      13. <p> 完成一个有趣的游戏(类似抢板凳):主线程中创建线程1,然后线程1再创建2个线程2,3,线程2,3分别对一个计数器操作counter(初值为0), 线程1每使用一次加3,线程2每使用一次加5,如果加到被15整除,那么counter加8,看哪个线程先加到9999,并计算自己使用了多少次计算器。 先到者胜利,并打印出相应信息。</p>  
      14. <p>实现代码:</p>  
      15. <p></p>  
      16. <pre name="code" class="cpp">#include<pthread.h>  
      17. #include<stdlib.h>  
      18. #include<unistd.h>  
      19. #include<stdio.h>  
      20.    
      21. #defineCOUNTER_MAX 9999  
      22. static intCOUNTER;  
      23. struct RESULT {  
      24.     pthread_t tid;  
      25.     int cnt1;  
      26.     int cnt2;  
      27. };  
      28. static structRESULT res;  
      29. staticpthread_mutex_t   mux  = PTHREAD_MUTEX_INITIALIZER;  
      30. staticpthread_cond_t    cond =PTHREAD_COND_INITIALIZER;  
      31.    
      32.    
      33. static void *thread2(void *arg)  
      34. {  
      35.     int ret;  
      36.    
      37.     printf("enter thread2, tid =%lu ",pthread_self());  
      38.     sleep(1);  
      39.     for (;;) {  
      40.        pthread_mutex_lock(&mux);  
      41.         if(COUNTER >= COUNTER_MAX) {  
      42.            ret = pthread_cond_signal(&cond); //唤醒一个因条件变量cond而阻塞的线程  
      43.            if (ret) printf("error in thread2 ");  
      44.            res.tid = pthread_self();  
      45.            pthread_mutex_unlock(&mux); //释放mux  
      46.            pthread_exit(0);        
      47.         }  
      48.        printf(".");  
      49.        fflush(stdout);  
      50.        COUNTER += 3;  
      51.         if(COUNTER%15 == 0 && COUNTER) {  
      52.            COUNTER += 8;  
      53.            usleep(50*res.cnt1);  
      54.         }  
      55.        res.cnt1++;  
      56.        pthread_mutex_unlock(&mux);  
      57.        usleep(COUNTER);  
      58.     }  
      59. }  
      60.    
      61. static void *thread3(void *arg)  
      62. {  
      63.     int ret;  
      64.    
      65.     printf("enter thread3, tid =%lu ",pthread_self());  
      66.     sleep(1);  
      67.     for (;;) {  
      68.        pthread_mutex_lock(&mux);  
      69.         if(COUNTER >= COUNTER_MAX) {  
      70.            ret = pthread_cond_signal(&cond); //唤醒一个因条件变量cond而阻塞的线程  
      71.            if (ret) printf("error in thread3 ");  
      72.            res.tid = pthread_self();  
      73.            pthread_mutex_unlock(&mux); //释放mux  
      74.            pthread_exit(0);  
      75.         }  
      76.        printf("o");  
      77.        fflush(stdout);  
      78.        COUNTER += 5;  
      79.         if(COUNTER%15 == 0 && COUNTER) {  
      80.            COUNTER += 8;  
      81.                 usleep(50*res.cnt2);  
      82.         }  
      83.        res.cnt2++;  
      84.        pthread_mutex_unlock(&mux);  
      85.        usleep(COUNTER);   
      86.     }  
      87. }  
      88.    
      89. static void *thread1(void *arg)  
      90. {  
      91.     int ret;  
      92.     pthread_t tid2,tid3;  
      93.         printf("starting... ");  
      94.     pthread_mutex_lock(&mux);  
      95.     ret =pthread_create(&tid2,NULL,thread2,NULL);  
      96.     if (ret) {  
      97.        printf("create thread1 error ");  
      98.     }  
      99.      
      100.     ret =pthread_create(&tid3,NULL,thread3,NULL);  
      101.     if (ret) {  
      102.        printf("create thread2 error ");   
      103.     }  
      104.     pthread_cond_wait(&cond,&mux);   //释放mux,等待cond为真  
      105.     if (res.tid == tid2) {  
      106.             pthread_cancel(tid2);  
      107.     }  
      108.     else {  
      109.        pthread_cancel(tid3);  
      110.     }  
      111.         printf(" get the winner: %s, tid= %lu,",(res.tid==tid2?"thread2":"thread3"),res.tid);  
      112.     printf("cnt1 = %d,cnt2 =%d ",res.cnt1,res.cnt2);  
      113.     pthread_mutex_unlock(&mux);  
      114.     pthread_exit(0);  
      115. }  
      116.    
      117. int main(void)  
      118. {  
      119.     int ret;  
      120.     pthread_t tid1;  
      121.    
      122.     ret =pthread_create(&tid1,NULL,thread1,NULL);  
      123.     if (ret) {  
      124.        printf("create thread1 error ");  
      125.     }  
      126.      
      127.     if (pthread_join(tid1,NULL)) { //等待thread1结束  
      128.       printf("error in thread1 ");  
      129.     }  
      130.    
      131.     exit(0);  
      132. }</pre>  
      133. <p></p>  
      134. <p>测试结果:</p>  
      135. <p></p>  
      136. <pre name="code" class="cpp">starting...  
      137. enter thread3, tid= 3062217584  
      138. enter thread2, tid= 3070610288  
      139. o..o.o.o.o.o.o.o.o.oo..oo..o.o.o..oo..oo..o.o.o..oo..oo.o.o.o.o.o.o.o.o.o..oo..oo.o.o.o.o.o.o.o..oo.o..oo..o.o.o.o.o.o.o..o.oo.o.oo..oo.o.o.o.oo.o.o.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.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o..o.o.o.o.o.o.o..o.o..o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o..o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.oo.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o.o  
      140. get the winner:  
      141. thread2, tid =3070610288,cnt1 = 1046,cnt2 = 1072</pre>  
      142. <p></p>  
      143. <p style="margin-bottom:0cm" align="LEFT"><br>  
      144. </p>  
      145. <pre></pre>  
      146. <pre></pre>  
      147. <pre></pre>  
      148. <pre></pre>  
      149. <pre></pre>  
      150. <pre></pre>  
      151. <pre></pre>  
      152. <pre></pre>  
      153.     

        转载自:http://blog.csdn.net/yyplc====

  • 相关阅读:
    2020软件工程第四次作业04
    2020软件工程作业02
    2020软件工程作业01
    2020软件工程个人作业06——软件工程实践总结作业
    2020软件工程作业05
    2020软件工程作业00—问题清单
    2020软件工程作业03
    2020软件工程作业02
    2020软件工程作业01
    小小小-冲刺集合
  • 原文地址:https://www.cnblogs.com/oracleloyal/p/5305280.html
Copyright © 2020-2023  润新知