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 ~]#

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

  • 相关阅读:
    lanya
    Apple watch ,小米微信通知
    jenkins grunt 自动构建流程
    刷机步骤
    ipad忘记了锁屏密码,已经越狱了
    ar
    如何在ubuntu中安装php
    阿里云
    docker swarm 集群及可视化界面的安装及配置
    https://github.com/gaoyangxiaozhu/DockerVI
  • 原文地址:https://www.cnblogs.com/Robotke1/p/3055069.html
Copyright © 2011-2022 走看看