这两个循环同时工作,同时是无限的,这是必要的。我以前用Java和Python做过这件事,但是当我尝试用C语言做这件事时,我遇到了一个问题。
如果我在Java中这样做的话:
public static void main(String[] args)
{
    new Thread(new Runnable()
    {
        @Override
        public void run()
        {
            while (true)
            {
                // some code
            }
        }
    }).start();
    while (true)
    {
        // some code
    }
}或者在Python中:
def thread():
    while True:
        # some code
def main():
    t = threading.Thread(target = thread)
    t.start()
    while True:
        # some code
if __name__ == '__main__':
    main()好吧,但是当我用C语言这么做的时候:
void *thread(void *args)
{
    while (1)
    {
        // some code
    }
}
int main()
{
    pthread_t tid;
    pthread_create(&tid, NULL, thread);
    pthread_join(tid, NULL);
    while (1)
    {
        // some code
    }
    return 0;
}只有线程中的循环运行,编译器在创建线程后根本不读取代码。那怎么做呢?
发布于 2017-06-21 14:59:55
pthread_join函数告诉调用线程等待给定线程完成。由于您启动的线程从未结束,main将永远等待。
摆脱该函数,允许主线程在启动子线程后继续运行。
int main()
{
    pthread_t tid;
    pthread_create(&tid, NULL, thread);
    while (1)
    {
        // some code
    }
    return 0;
}https://stackoverflow.com/questions/44679608
复制相似问题