2017-01-04 53 views
1

我有使用Pthread創建線程的問題。 我認爲有人可以應付問題出在哪裏。 我的代碼如下。由於空間限制,我只顯示一些部分。從pthread創建返回代碼是11

 Main.c create Detectdirection instance and send to the function. 

    d = new Detectdirection();  
    while(run) 
    {     
     int ret = d->run_parallel(d); 
     if(ret == -1) 
      run = false; 
    } 

我的Detectdirection類有兩個函數可以並行運行。

class Detectdirection{ 
    public: 
     int run_parallel(void*p); 
     void *Tracking(void *p); 
     static void *Tracking_helper(void * p); 
     void *ReadImage(void *p); 
     static void *ReadImage_helper(void *p); 
    private: 
     pthread_t thread[2]; 


} 
void *Detectdirection::ReadImage(void *p){ 
    Detectdirection *app = (Detectdirection*)p; 
    while(run){ 

    } 
    pthread_exit(NULL); 
} 
void *Detectdirection::Tracking(void *p){ 
    Detectdirection *app = (Detectdirection*)p; 
    while(run){ 

    } 
    pthread_exit(NULL); 
} 

void *Detectdirection::Tracking_helper(void *p){ 
    Detectdirection *app = (Detectdirection*)p; 
    return ((Detectdirection*)p)->Tracking(app); 
} 
void *Detectdirection::ReadImage_helper(void *p){ 
    Detectdirection *app = (Detectdirection*)p; 
    return ((Detectdirection*)p)->ReadImage(app); 
} 
int Detectdirection::run_parallel(void* p){ 
      Detectdirection *app = (Detectdirection*)p; 
     int rc = pthread_create(&thread[0], NULL, app->ReadImage_helper, app); 
     if (rc) { 
     printf("ERROR; return code from pthread_create() is %d\n", rc); 
     return -1; 
     } 

     rc = pthread_create(&thread[1], NULL, app->Tracking_helper, app); 
     if (rc) { 
     printf("ERROR; return code from pthread_create() is %d\n", rc); 
     return -1; 
     } 

     return 0; 
} 

編譯是好的,當我運行時,我有線程創建錯誤。只有在創建多個線程時,纔會發生那種類型的返回類型11。但是現在我只創建了兩個線程,並且出現了這個錯誤。什麼可能是錯的?

回答

1

我相信你會得到EAGAIN(根據錯誤代碼11)。這(明顯)意味着你的系統沒有足夠的資源來創建線程了。

POSIX documentation說:

[EAGAIN]系統缺乏必要的資源來創建另一個 線程,或 過程{PTHREAD_THREADS_MAX}上的線程總數的系統強加的限制將被突破。

我不太確定以下是真的。

但是現在我只創建了兩個線程,並且出現了該錯誤。什麼可能是錯的?

這裏,

while(run) 
    {     
     int ret = d->run_parallel(d); 
     if(ret == -1) 
      run = false; 
    } 

您正在創建一個循環,每次調用d->run_parallel()創建兩個線程。因此,您可能會創建無限數量的線程 ,因爲循環僅在pthread_create()失敗時纔會中斷。所以,你可能想仔細看看這個循環,不管你現在是否真的想要這樣做。

你似乎沒有加入你創建的線程。因此,您可以將分開這些線程,以便在線程退出時立即釋放線程特定的資源。 你可以這樣做:

pthread_detach(pthread_self()); 

兩個ReadImage_helper()Tracking_helper()功能分開他們。這可能潛在地解決您的資源問題。

如果它仍然存在,那麼你必須考慮限制同時在系統上運行的線程數的方法。一種可能的選擇是使用thread pools - 創建固定數量的線程並在線程完成其當前任務時爲其分配新任務。

+0

是的我在Main有錯誤,我不應該使用while循環。它會創建很多線程。 – batuman