简体   繁体   中英

Thread termination difference between C & Java

From my understanding, a C process will be terminated as soon as the main (parent) thread returns or reaches the end of execution. (This can be changed using pthread_join in the main thread).

However, a Java process will still keep running until all the threads finishes their execution even if the main thread has returned or finished. (This can be changed by making the child threads run as daemons in Java).

Why did Java choose to do it this way?

C code sample:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>

pthread_t tid[2];

void *doSomeThing(void *arg) {
    unsigned long i = 0;
    pthread_t id = pthread_self();

    if (pthread_equal(id, tid[0])) {
        printf("\n First thread processing\n");
    }
    else {
        printf("\n Second thread processing\n");
    }

    for (i = 0; i < (0xFFFFFFFF); i++);

    printf("\n Threads finished.\n");
    return NULL;
}

int main() {
    int i = 0;
    int err;

    while(i < 2)
    {
        err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);
        if (err != 0)
            printf("\ncan't create thread :[%s]", strerror(err));
        else
            printf("\n Thread created successfully\n");

        i++;
    }

    sleep(2);
    printf("\nProcess Exit\n");
    return 0;
}

C Output

Thread created successfully

First thread processing

Thread created successfully

Second thread processing

Process Exit

Neither thread finishes it's task before process exits.

However, in Java:

Java Code Sample

public class ThreadTermination implements Runnable {

    @Override
    public void run() {
        System.out.println("Thread running.");
        try {
            Thread.sleep(5 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Thread ending.");
    }

    public static void main(String[] args) {
        ThreadTermination t1 = new ThreadTermination();
        ThreadTermination t2 = new ThreadTermination();

        Thread thr1 = new Thread(t1);
        System.out.println("Thread 1 starting.");
        thr1.start();
        Thread thr2 = new Thread(t2);
        System.out.println("Thread 2 starting.");
        thr2.start();

        System.out.println("Main thread finished.");
    }
}

Java Ouptut

Thread 1 starting.
Thread 2 starting.
Thread running.
Main thread finished.
Thread running.
Thread ending.
Thread ending.

Both threads completes its task even though the main thread has finished long back. As can be seen, there are no daemon threads.

Edit: From Java doc :

The Java Virtual Machine continues to execute threads until all threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method

From my understanding, a C process will be terminated as soon as the main (parent) thread returns or reaches the end of execution.

No. AC process will not terminate just because the first thread reaches the end of its execution. To prove it, change your code from:

    sleep(2);
    printf("\nProcess Exit\n");
    return 0;
}

To:

    sleep(2);
    printf("\nThread Exit\n");
    pthread_exit(0);
    return 0; // will never execute
}

The process will terminate if the first thread returns from main . The C standard (section 5.1.2.2.3) says that returning from main is equivalent to calling exit , and this is what terminates the process. The thread then terminates because the process terminates, not the other way around.

Your statement is incorrect in several aspects:

  1. The Java application will exit upon the main thread terminates, unless you have any daemon threads.

  2. And the C++ program won't immediately terminate - after the main thread finishes, there are still clean up to do before the entire process is finished.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM