`
shaojiashuai123456
  • 浏览: 256825 次
  • 性别: Icon_minigender_1
  • 来自: 吉林
社区版块
存档分类
最新评论

c线程基础

阅读更多

需要引入头文件 #include<pthread.h>

1.创建线程

  int

  pthread_create(pthread_t  *pid,const phread_attr_t *attr,void *(*handler)(void *),void *hand_attr);

 

        (1)pid 表示创建线程的id指针

        (2)attr表示线程的属性,如果为NULL,表示默认设置

        (3)handler表示一个回调函数,即线程所要运行的函数

        (4)hand_attr 表示回调函数参数地址

        返回值类型为int ,0 表示创建成功,非0表示不成功。

    

2.等待线程结束

  int

  pthread_join(pthread_t *pid,void **value_ptr)

        (1)pid 表示创建的线程的id指针

        (2)value_ptr 表示返回值地址指针存放位置的指针

        返回类型为int , 0表示结束成功,非0表示不成功。

3.线程结束

  void pthread_exit(void *value_ptr)

        (1)value_ptr 表示返回值指针

 

 例子

 

#include <stdio.h>
#include <pthread.h>

void * handler1(void *arg)
{
    int i;
    for(i=0;i<3;i++)
    {
         printf("handler1\n");
         sleep(1);
    }
}
void * handler2(void *arg)
{
    int i;
    for(i=0;i<4;i++)
    {
         printf("handler2\n");
         sleep(1);
    }
}

int main(int argc, char *argv[])
{
    //声明2个线程id
    pthread_t pid1;
    pthread_t pid2;
    //创建2个线程
    printf("begin\n");
    if(pthread_create((pthread_t *)&pid1,NULL,(void*)handler1,NULL))
    {
           printf("can't create new thread\n");
           return -1;
    }
    if(pthread_create((pthread_t *)&pid2,NULL,(void*)handler2,NULL))
    {
          printf("can't create new thread\n");
          return -1;
    }
 
    //等待2个线程结束
    if(pthread_join(pid1,NULL))
    {
       	   printf("can't join thread\n");
       	   return -1;
    }
    if(pthread_join(pid2,NULL))
    {
        	printf("can't join thread\n");
          	 return -1;
    }  
    printf("over\n");
    return 0;
}

   linux 编译与运行

    
 
  

   运行结果

 
 
 

       

  • 大小: 860 Bytes
  • 大小: 725 Bytes
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics