2015-07-03 22 views
0
main() 
{ 
    i=9000000000;  // to synchronize thread with while loop 
    while(i)i--;  //if i don't use these two lines then my program terminates before thread starts. 
    udp_socket(); 
    fun(); 
} 

udp_socket() 
{ 
    // open a udp socket then create thread 
    pthread_create(tid1,NULL,fun2,(int *)socket_descriptor2); 
} 

fun() 
{ 
} 

fun2(int socket_descriptor2) 
{ 
    while(1) 
    { 
    } 
} 
  1. 線程同步我打開UDP套接字然後創建線程,線程內while循環時間可持續recieving所定義的IP地址和端口的數據。與主()

  2. 我當主終止.....

  3. 我要執行我的線程持續,即使在main()終止或我的main()也不斷沒有終止執行線程停止工作。

我該如何執行此操作?

+2

該程序沒有任何意義。 '我'什麼?九十億?沒有原型?請告訴我,該程序編譯沒有錯誤或*警告*。更不用說格式了。您*知道如何創建一個[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)? –

+0

順便說一句,您可能想要搜索並閱讀* detached threads *或'pthread_exit',或者只是分叉一個新進程。 –

+0

使用while循環進行同步完全是錯誤的方式(通常)。即使你在某個時候開始工作,它也會非常依賴時序和系統,因此很可能在其他某個時候失敗。您需要與爲此目的而設計的機制(如信號量,互斥鎖,管道,等待,連接等)進行同步。併發是一個完整的計算機科學主題,因此如果您尚不知道理論,那麼最好從獲得基本理解開始在嘗試編寫多線程應用程序之前。 – kaylum

回答

1

我想繼續執行,甚至我的線程,當主()結束

要通過呼叫pthread_exit()這樣做出口int main()

int main(void) 
{ 
    ... 

    pthread_exit(NULL); /* This call exits main() and leaves all other thread running. */ 

    return 0; /* Is never reached, it's just there to silence the compiler. */ 
} 
+0

感謝了pthread_exit(NULL)工作 – kabhis

1

如果你不想讓你的main過早終止,使其至少等待線程終止。假設你有tid1訪問在你的主,到pthread_join(tid1,NULL)一個簡單的通話將讓主線程等待。

+0

如果我使用pthread_detach代替pthread_join,那很好嗎? – kabhis

+0

沒有'pthread_detach'不會解決你的問題:你需要(據我所知)讓你的'main'等待一些條件終止。 –

+0

@thanks讓 - 巴蒂斯特Yunès – kabhis

1

在下面示例main等待線程完成(fun2返回)。當您在stdin上輸入整數時,fun2會返回。

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

void fun() { 
    printf("Hello from fun\n"); 
} 

void fun2() { 
    int a; 
    scanf("%d", &a); 
} 

pthread_t udp_socket() { 
    pthread_t tid; 
    pthread_create(&tid,NULL,fun2,NULL); 
    return tid; 
} 

int main() { 
    void * ret = NULL; 
    pthread_t t = udp_socket(); 
    fun(); 
    if(pthread_join(t, &ret)) {    // Waits for thread to terminate 
    printf("Some Error Occurred\n"); 
    } 
    else { 
    printf("Successfully executed\n"); 
    } 

Here是關於pthread_join的更多信息。