zoukankan      html  css  js  c++  java
  • Linux 在线程中创建线程,在线程中等待线程

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <semaphore.h>
    #include <dirent.h>
    #include <pthread.h>
    #include <time.h>
    
    void* task2(void* arg)
    {
        int i = 0;
        while (i++ < 10)
        {
            sleep(1);
            printf("task2 running...\n");
        }
    
        printf("task2 exit...\n");
        return NULL;
    }
    
    void* task1(void* arg)
    {
        pthread_t tid;
        pthread_create(&tid, NULL, (void*)task2, NULL);  // 创建线程2
        pthread_join(tid, NULL);  // 等待线程2退出
    
        printf("task1 exit...\n");
        return NULL;
    }
    
    int main(int argc, char *argv[])
    {
        pthread_t tid;
    
        pthread_create(&tid, NULL, (void*)task1, NULL);    // 创建线程1
        pthread_join(tid, NULL);    // 创建线程1退出
    
        printf("Main thread exit...\n");
    
        return 0;
    }

    程序输出:

    [root@localhost ~]# gcc thread_running.c -lpthread -o thread_running
    [root@localhost ~]# ./thread_running
    task2 running...
    task2 running...
    task2 running...
    task2 running...
    task2 running...
    task2 running...
    task2 running...
    task2 running...
    task2 running...
    task2 running...
    task2 exit...  // 线程2退出
    task1 exit...  // 线程1退出
    Main thread exit...  // 主线程退出
    [root@localhost ~]#

    总结:在线程中创建线程,在线程中等待线程,等待只是为了回收资源。

  • 相关阅读:
    iptables
    linux时间同步
    iftop使用
    linux目录结构及定时任务
    awk基本用法
    二、Java面向对象(6)_深入变量
    二、Java面向对象(5)_static修饰符
    二、Java面向对象(4)_构造函数
    二、Java面向对象(3)_类和对象
    二、Java面向对象(2)_软件开发方式
  • 原文地址:https://www.cnblogs.com/Robotke1/p/3055069.html
Copyright © 2011-2022 走看看