pthread 线程

 

1.线程的创建

  int ret  = pthread_create(&thdid,NULL,th_func,void *p);

  

 th_func 执行程序任务  创建成功返回 0 

  thid --->pthread_t 是线程号,在这里做传出参数。

   p 是th_func 的参数,使用时需要强制转换为void *

void* thread(void* p)
{ //线程的开始
    int i=(int)p;//强制转换为整型
    printf("I am child thread %d\n",i);
    while(1);
}//线程结束

int main()
{
    pthread_t th_id;
    int ret=pthread_create(&th_id,NULL,thread,(void*)5);//创建线程,将数值放入指针内
    if(ret!=0)
    {
        printf("pthread_create failed ret=%d\n",ret);
        return -1;
    }
    while(1);
    return 0;
}
View Code

 

2.线程等待

  void* p1;
  int ret = pthread_join( th_id, &p1 );//int pthread_join(pthread_t,void **p);

  这里void *p1是上面所用的线程在退出时用pthread_exit时的参数,在这里也做传出参数使用。thid自然就是其等待的线程id

ex:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
//创建线程,通过pthread_join拿到我们的线程的返回值

//线程函数
void* thread(void* p)
{ //线程的开始
    strcpy((char*)p,"hello");
    printf("I am child thread\n");
    printf("child p is %p\n",p);
    pthread_exit(p);//通过pthread_exit实现线程退出,没有返回值,就写pthread_exit(NULL);
}//线程结束

int main()
{
    pthread_t th_id;
    void* p=malloc(20);
    printf("p is %p\n",p);
    int ret=pthread_create(&th_id,NULL,thread,p);//创建线程,将数值放入指针内
    if(ret!=0)
    {
        printf("pthread_create failed ret=%d\n",ret);
        return -1;
    }
    void* p1;    
    ret=pthread_join(th_id,&p1);
    if(ret!=0)
    {
        printf("pthread_join failed ret=%d\n",ret);
        return -1;
    }
    printf("main thread %s\n",(char*)p);
    printf("main thread p1=%p\n",p1);
    return 0;
}
View Code

 

3.线程退出

  pthread_exit(void *);一般在子线程结束需要传出参数时使用;

void* thread(void* p)
{ //线程的开始
    strcpy((char*)p,"hello");
    printf("I am child thread\n");
    printf("child p is %p\n",p);
    pthread_exit((void*)0);//通过pthread_exit实现线程退出,没有返回值,就写pthread_exit(NULL);
}//线程结束
View Code

4.线程申请内存问题

  子线程申请内存后,当子线程推出后,其他线程仍然可以使用内存。

转载于:https://www.cnblogs.com/STARK-INDUSTRIES/p/5656914.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值