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

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

  • 相关阅读:
    卢卡斯定理算法模板
    求组合数的O(n^2)和O(n)解法及模板
    求逆元的方法及模板
    扩展欧基里德算法模板
    牛客练习赛43-F(简单容斥)
    容斥原理
    牛客网练习赛43-C(图论)
    折半搜索
    枚举+树状数组(经典)
    思维并查集/网络流和二分
  • 原文地址:https://www.cnblogs.com/Robotke1/p/3055069.html
Copyright © 2011-2022 走看看