线程-1-2--线程等待及退出

可能会考:1.进程和线程的区别(空间)

                  2 线程优点(通信,“节俭”)

学习这篇文章中有关线程的相关知识。
链接: Linux多线程编程初探 - 峰子_仰望阳光 - 博客园.

线程的创建

int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
// 返回:若成功返回0,否则返回错误编号
参数1:线程id
参数2:线程属性 (null)                                                                                 参数3:调用相关函数(函数指针)
参数4:给线程传参的参数
注意:参数3和4是配合使用的     
      pthread_t pthread_self(void);(类似pid)
// 返回:调用线程的ID

下面运行小段代码

void*fund(void*arg){

    printf("ti pthread create success!!!\n");
    printf("t1  id  is= %ld\n",(unsigned long)pthread_self());
    printf("arg  is =%d\n",*((int*)arg));
}

int main(){

int ret;
pthread_t t1;
int arg=100;
//pthread_t pthread_self(void);

     ret=pthread_create(&t1,NULL,fund,(void*)&arg);
    if(ret==0){
          printf("pthread create success!!!\n");
        }

     printf("main id is = %ld \n",(unsigned long)pthread_self());

      while(1);
运行结果为  gcc demo1.c -pthread
CLC@Embed_Learn:~/thread$ gcc demo1.c -pthread
CLC@Embed_Learn:~/thread$ ./a.out
pthread create success!!!
main id is = 140354439034624 
ti pthread create success!!!
t1  id  is= 140354430756608
arg  is =100
如果while(1)没有的情况下,必须来调用 
线程等待:调用该个函数的线程将阻塞,第一个参数为线程t1的id号
                                 第二个参数   1.NULL (不需要获取t1线程中的数据)
                                             2.(void**)ter 将t1中的数据给ter
此时必使用退出线程来退出t1线程   
pthread_exit(void *rval_ptr);   参数:将线程里面的数据带出去,给等待函数                                                                           

  既可以传整数,也可以传字符串,但是如果传多个数据,就必须参数改为结构体

以下是传的整数

void*fund(void*arg){
    static int data=666;
    pthread_exit((void *)&data);

}


int*ter=NULL;

 pthread_join(t1, (void **)&ter);
    printf("tet data is =%d\n",*ter);

    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

追着太阳跑1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值