• 线程的概述


    #include

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

        功能:创建一个子线程

        参数:

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

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

            -start_routine:函数指针,这个函数是子线程需要处理的逻辑代码

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

        返回值:成功:0

        失败:返回错误号

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

    1. #include
    2. #include
    3. #include
    4. #include
    5. void * callback(void * arg) {
    6. printf("child thread...");
    7. return NULL;
    8. }
    9. int main() {
    10. pthread_t tid;
    11. int ret = pthread_create(&tid, NULL, callback, NULL);
    12. if(ret != 0) {
    13. char* errstr = strerror(ret);
    14. printf("error: %s\n", errstr);
    15. }
    16. for(int i = 0; i < 5; i++) {
    17. printf("%d\n", i);
    18. }
    19. sleep(1);
    20. return 0;
    21. }

    #include

        int pthread_join(pthread_t thread, void **retval);

        功能:和一个已经终止的线程进行连接,回收子线程的资源,这个函数是阻塞函数,调用一次只能回收一个子线程,一般在主线程中使用

        参数:

            -thread:线程ID

            -retval:接收子线程退出时的返回值

        Compile and link with -pthread.

    1. #include
    2. #include
    3. #include
    4. #include
    5. void* callback(void* arg) {
    6. printf("child thread id : %ld\n", pthread_self());
    7. sleep(3);
    8. return NULL;
    9. }
    10. int main() {
    11. pthread_t tid;
    12. int ret = pthread_create(&tid, NULL, callback, NULL);
    13. if(ret != 0) {
    14. char* errstr = strerror(ret);
    15. printf("errnum: %s\n", errstr);
    16. }
    17. for(int i = 0; i < 5; i++) {
    18. printf("%d\n", i);
    19. }
    20. ret = pthread_join(tid, NULL);
    21. if(ret != 0) {
    22. char* errstr = strerror(ret);
    23. printf("errnum: %s\n", errstr);
    24. }
    25. printf("回收子线程资源成功!\n");
    26. pthread_exit(NULL);//让主线程退出,对其他线程没有影响
    27. return 0;
    28. }

  • 相关阅读:
    Linux 环境Skywalking部署Elasticsearch
    Linux综合使用练习
    【C语言】字符函数和字符串函数
    python操作kafka
    [MIT 6.830 SimpleDB] Lab1 Exercise 1-3
    2021最新中高级Java面试题目,Java面试题汇总
    【Python零基础入门篇 · 9】:字典的相关操作
    通义千问:一个专门响应人类指令的大模型
    《算法通关村第二关黄金挑战一一K个一组反转》
    (Note)Elsevier爱思唯尔期刊投稿流程
  • 原文地址:https://blog.csdn.net/ME_Liao_2022/article/details/133394559