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

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

你可能感兴趣的:(linux)