简体   繁体   English

无限循环实际上停止使用线程

[英]A while infinte cycle actually stops using threads

I'm new to C and I am trying to learn.我是 C 的新手,我正在努力学习。 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);如果你希望你的程序永远不会结束,你应该添加一个while(1); at the end of you main while loop.在你的主 while 循环结束时。

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.请注意,这不是正确执行此操作的方法,您的线程应该结束,并且主线程应该等待所有线程完成,然后再退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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