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

      

  • 相关阅读:
    阿里云与物理服务器
    ## 100个网路基础知识##
    Linux 中vim编辑器
    Linux 目录结构及增删改查
    Linux 命令行常用快捷键
    XSS劫持cookie登录
    Tomcat
    centos 6.5 搭建DHCP实验
    centos 6.5 系统故障分析实验
    LVM的创建及管理
  • 原文地址:https://www.cnblogs.com/xzxl/p/8556336.html
Copyright © 2011-2022 走看看