zoukankan      html  css  js  c++  java
  • 转:pthread_create()

    http://blog.csdn.net/youbang321/article/details/7815707

     

    原型:int  pthread_create((pthread_t  *thread,  pthread_attr_t  *attr,  void  *(*start_routine)(void  *),  void  *arg)

        用法:#include  <pthread.h>

        功能:创建线程(实际上就是确定调用该线程函数的入口点),在线程创建以后,就开始运行相关的线程函数。

        说明:thread:线程标识符;

                  attr:线程属性设置;

                  start_routine:线程函数的起始地址;

                  arg:传递给start_routine的参数;

                  返回值:成功,返回0;出错,返回-1。

        举例:

    [cpp] view plain copy
     
     print?
    1. /*thread.c*/  
    2. #include <stdio.h>  
    3. #include <pthread.h>  
    4.   
    5. /*线程一*/  
    6. void thread_1(void)  
    7. {  
    8.     int i=0;  
    9.     for(i=0;i<=6;i++)  
    10.     {  
    11.         printf("This is a pthread_1. ");  
    12.         if(i==2)  
    13.             pthread_exit(0);  
    14.         sleep(1);  
    15.     }  
    16. }  
    17.   
    18. /*线程二*/  
    19. void thread_2(void)  
    20. {  
    21.     int i;  
    22.     for(i=0;i<3;i++)  
    23.         printf("This is a pthread_2. ");  
    24.     pthread_exit(0);  
    25. }  
    26.   
    27. int main(void)  
    28. {  
    29.     pthread_t id_1,id_2;  
    30.     int i,ret;  
    31. /*创建线程一*/  
    32.     ret=pthread_create(&id_1,NULL,(void  *) thread_1,NULL);  
    33.     if(ret!=0)  
    34.     {  
    35.         printf("Create pthread error! ");  
    36.     return -1;  
    37.     }  
    38. /*创建线程二*/  
    39.      ret=pthread_create(&id_2,NULL,(void  *) thread_2,NULL);  
    40.     if(ret!=0)  
    41.     {  
    42.         printf("Create pthread error! ");  
    43.     return -1;  
    44.     }  
    45. /*等待线程结束*/  
    46.     pthread_join(id_1,NULL);  
    47.     pthread_join(id_2,NULL);  
    48.     return 0;  
    49. }  

        以下是程序运行结果:

         备注:pthread库不是Linux系统默认的库,连接时需要使用静态库libpthread.a,所以在线程函数在编译时,需要连接库函数,如上图    gcc pthread_create.c -o pthread_create -lpthread

     
     
  • 相关阅读:
    【光学相机】关于网络通信的方法及函数
    InvokeRequired与Invoke
    线程基本概念
    线程同步与线程异步
    AutoResetEvent和ManualResetEvent
    C#图像亮度调式与伪彩色图的处理
    Github文件高速下载方法
    JDK11以上版本没有JRE的解决方法
    mysql 随机函数生成某个范围内的整数
    mysql主键id重置
  • 原文地址:https://www.cnblogs.com/yfz0/p/5800452.html
Copyright © 2011-2022 走看看