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

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

  • 相关阅读:
    kali linux DVWA config 问题解决方案
    HashMap&线程
    Synchronized和java.util.concurrent.locks.Lockde区别联系
    线程池
    信息嗅探
    java子类对象和成员变量的隐写&方法重写
    Java中Super和final关键字以及异常类
    523. Continuous Subarray Sum
    494. Target Sum
    477. Total Hamming Distance
  • 原文地址:https://www.cnblogs.com/Robotke1/p/3055069.html
Copyright © 2011-2022 走看看