简体   繁体   中英

A while infinte cycle actually stops using threads

I'm new to C and I am trying to learn. I'm trying to implement multithreading in my program, but I'm having problems. The program (and the threads) should be going on running in a infinite loop, but actually the programs stops after few seconds. What can I do for having the program running forever? Am I doing something wrong?

#include <stdio.h>
#include <pthread.h>


void *func(void *threadid){
    while (1)
    {
        /* do stuff, but the program terminates after that thread does few cycles */
    }
}

int main(){
    #define NUM_THREADS 800
    pthread_t threads[NUM_THREADS];
    int rc, i;
    for (i=0; i < NUM_THREADS; i++)
    {
        rc = pthread_create(&threads[i], NULL, func, (void *)i);
        if (rc)
        {
            printf("Error to create thread, #%d\n", rc);
            exit(-1);
        }
    }
    pthread_exit(NULL);
}

As soon as your main thread exits, the program terminates (and so do the threads). If you want your program to never end, you should add a while(1); at the end of you main while loop.

Note that this is not how to do it properly, your threads should have an end, and the master thread should wait for all the threads to be done, before exiting itself.

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