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;
    }
    

      

  • 相关阅读:
    AD用户移除所属组
    Mysql中文乱码问题完美解决方案
    将sqllite3数据库迁移到mysql
    检查远端服务器端口是否打开
    远程桌面卡
    不同平台的线程并发接口对比
    stm32之中断配置
    stm32之CMSIS标准、库目录、GPIO
    stm32 中断几个库函数实现过程分析
    Tree命令使用
  • 原文地址:https://www.cnblogs.com/xzxl/p/8556336.html
Copyright © 2011-2022 走看看