zoukankan      html  css  js  c++  java
  • 自测之Lesson14:多线程编程

    题目:创建一个线程,并理清主线程结束时会发生什么。

    代码:

    #include <stdio.h>
    #include <pthread.h>
    #include <unistd.h>
    
    void func()
    {
            fprintf(stderr, "Thread has been created!
    ");
            return;
    }
    
    
    int main()
    {
            pthread_t tid;
            printf("Create thread1...
    ");
            pthread_create(&tid, NULL, (void*)func, NULL);
            printf("main() begin sleep...
    ");
            sleep(5);                       // 防止父进程退出导致线程结束,而使得其调用函数无法执行
            printf("main() end sleep...
    ");
            return 0;
    }
    

      

    题目:创建一个线程,并使用join函数等待线程结束。

    完成代码:

    #include <stdio.h>
    #include <pthread.h>
    #include <unistd.h>
    
    void func()
    {
            fprintf(stderr, "Thread has been created!
    ");
            pthread_exit(NULL);
            return;
    }
    
    
    int main()
    {
            pthread_t tid;
            printf("Create thread1...
    ");
            pthread_create(&tid, NULL, (void*)func, NULL);
            pthread_join(tid, NULL);
            return 0;
    }
    

      

    题目:使用join函数完成传值功能。

    完成代码:

    #include <stdio.h>
    #include <pthread.h>
    #include <unistd.h>
    
    int retVal;
    void func()
    {
            retVal = 99; 
            fprintf(stderr, "Thread has been created!
    ");
            pthread_exit(&retVal);
    }
    
    
    int main()
    {
            pthread_t tid;
            printf("Create thread1...
    ");
            pthread_create(&tid, NULL, (void*)func, NULL);
            int *pRet;
            pthread_join(tid, (void*)&pRet);
            printf("retVal is %d
    ", *pRet);
            return 0;
    }
    

      

  • 相关阅读:
    看一看Vue.js
    Docker笔记
    Termux使用记录
    【Selenium】利用Cookies登录京东并添加商品至购物车以及结算
    GB 26149-2017 测试项目及要求
    【LeetCode】41. 缺失的第一个正数
    【数据结构】7. 排序
    【数据结构】6. 查找
    【数据结构】5. 图
    【数据结构】4. 树与二叉树
  • 原文地址:https://www.cnblogs.com/xzxl/p/8556336.html
Copyright © 2011-2022 走看看