2014-12-05 80 views
0

我想創建一個程序,每次調用特定方法時都會創建一個新線程。這是我的工作代碼到目前爲止:每次使用pthread調用方法時創建一個新線程

#define NUMBER_OF_THREADS 3 

pthread_t threads[NUMBER_OF_THREADS]; 
pthread_attr_t attr; 

void *BusyWork(void *t) 
{ 
    int i; 
    long tid; 
    tid = (long)t; 

    printf("Thread %ld running...\n",tid); 
    // ... 
    printf("Thread %ld completed...\n",tid); 

    pthread_exit((void*) t); 
} 

void createNewThread(int number){ 
    printf("running createNewThread(%d)\n", number); 
    pthread_t tid; 
    int rc = pthread_create(&tid, &attr, BusyWork, (void *) (long)number); 
    if (rc) { 
     printf("ERROR; return code from pthread_create() is %d\n", rc); 
     exit(-1); 
    } 
} 

int main(int argc, char *argv[]) { 
    int i, rc; 

    //Set up thread attributes 
    pthread_attr_init(&attr); 
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); 

    //Arbitary amount of calls (My real program will call the createNewThread() funcion multiple unkown amount of times) 
    createNewThread(15); 
    createNewThread(27); 
    createNewThread(62); 
    createNewThread(500); 
    createNewThread(8864); 
    createNewThread(99999); 

    //Free attributes 
    pthread_attr_destroy(&attr); 

    //Wait for other threads still running 
    // HOW CAN I DO THIS???? 
    /*for (i=0; i< NUMBER_OF_THREADS; i++){ 
     rc = pthread_join(??? , NULL); //TODO 
     if (rc){ 
      printf("ERROR: return code from pthread_join() %d\n", rc); 
      exit(-1); 
     } 
     printf("Main: completed join with thread %d\n", i); 
    }*/ 

    printf("Main: program completed. Exiting.\n"); 


    pthread_exit(NULL); // (?) Is this part nessassary as we are on the main thread and soon to exit the program 

    return 0; 
} 

但是,正如你可以在我的代碼中看到有幾個問題!例如,我如何等待所用的代碼完成所有進程,因爲我沒有跟蹤線程號。此外,當一個線程「忙碌」完成後,它不會自行清理並作爲孤立進程離開。

我想到的一個想法是使用一個向量來跟蹤每個線程號,然後將它用於main結尾處的最終連接。然而,問題在於數組列表很容易變得非常大,即使線程完成也不會縮小。

回答

2

分離線程,不要加入它們。在創建線程之前,增加一個受互斥鎖保護的計數器。在線程終止之前,獲取互斥量並遞減計數器。現在你知道當計數器讀數爲零時所有的線程都完成了。如果你喜歡,你可以使用條件變量使計數器等待。

+0

David,您的個人資料中有一個錯字:'crytpo-currency'。 – halfer 2018-01-15 17:31:55

相關問題