Linux 创建 终止线程(thread)

进程线程区别

创建线程

#include <pthread.h>

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);

    -功能:创建一个子线程,一般情况下main函数所在的线程称为主线程,其余的为子线程。

    -参数:

        -thread:传出参数,线程创建成功后,子线程的ID被写入这个变量

        -attr:设置线程的属性,一般使用默认值,NULL

        -start_routinue:函数指针,这个函数是子线程需要处理的函数

        -arg:给第三个参数使用,传参

    -返回值:

        - 成功:0

        -失败:返回错误号,和之前的错误号errno不太一样

        -获取错误的信息: char * strerror(int errnum)

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<pthread.h>
#include<string.h>

void * callback(void * arg) {
    printf("child thread");
    return NULL;
}


int main(){
    pthread_t tid;
    int ret = pthread_create(&tid, NULL, callback, NULL);
    if(ret != 0) {
        char * errstr = strerror(ret);
        printf("error: %s\n", errstr);
    }

    for(int i = 0; i < 5; i++) {
        printf("%d\n", i);
    }
    sleep(1);
    return 0;
}

终止进程

/*
    #include <pthread.h>
    void pthread_exit(void *retval);
    功能:终止一个线程,在哪个线程中调用,终止哪个
    参数:
        retval:传递一个指针,作为一个返回值,可以在pthread_join()中获取到

    int pthread_equal(pthread_t t1, pthread t2);
    功能:比较两个线程ID是否相等
        不同的操作系统实现pthread_t类型的方式不同,有的是无符号的长整型,有的是结构体
*/
#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<unistd.h>

void * callback(void* arg) {
    printf("child thread id %ld\n", pthread_self());
    return NULL;
}

int main() {
    pthread_t tid;
    int ret = pthread_create(&tid, NULL, callback, NULL);
    if(ret != 0) {
        char * strerr = strerror(ret);
        printf("error:%s\n", strerr);
    }

    for(int i = 0; i < 5; i++) {
        printf("%d\n", i);
    }

    printf("child thread id %ld, main tid: %ld\n", tid, pthread_self());

    //主线程退出,其他线程不受影响
    pthread_exit(NULL);

    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值