2017-06-21 173 views
1

這兩個週期必須同時工作,同時是無限的。我以前在Java和Python中做過這個,但是當我嘗試在C中做這件事時,我遇到了一個問題。如何讓兩個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() 

一切ok,但是當我做這在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; 
} 

只有循環在線程運行和編譯器根本不會在創建線程後讀取代碼。那麼如何做到這一點?

+5

你知道'pthread_join'嗎? –

+0

pthread_join永遠不會恢復,因爲您的原始線程永遠不會終止 – MrJman006

+0

「...並且編譯器在創建線程後根本不讀取代碼」 - 現在,這是一個轉折點。 –

回答

8

pthread_join函數告訴調用線程等待,直到給定的線程完成。由於你開始的線程永遠不會結束,main永遠等待。

擺脫該函數以允許主線程在啓動子線程後繼續。

int main() 
{ 
    pthread_t tid; 

    pthread_create(&tid, NULL, thread); 

    while (1) 
    { 
     // some code 
    } 

    return 0; 
}