2014-12-05 1 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; 
} 

그러나 내 코드에서 볼 수 있듯이 몇 가지 문제가 있습니다! 예를 들어 스레드 번호를 추적하지 않기 때문에 내가 사용하고있는 코드에 대한 모든 프로세스가 완료 될 때까지 기다릴 수 있습니다. 또한 "BusyWork"스레드가 완료되면 자체 스레드가 고아 프로세스로 남은 후에 정리하지 않습니다.

내가 가진 한 가지 아이디어는 벡터를 사용하여 각 스레드 번호를 추적 한 다음 주 끝에서 최종 결합에 사용하는 것이 었습니다. 그러나 그 문제는 어레이 목록이 쉽게 커질 수 있으며 스레드가 완료 되더라도 축소되지 않는다는 것입니다.

답변

2

스레드를 분리하고 결합하지 마십시오. 스레드를 만들기 전에 뮤텍스로 보호 된 카운터를 늘리십시오. 스레드가 종료되기 직전에 뮤텍스를 획득하고 카운터를 감소시킵니다. 이제 카운터가 0을 읽을 때 모든 스레드가 완료되었음을 알 수 있습니다. 원하는 경우 조건 변수를 사용하여 카운터를 대기 가능하게 만들 수 있습니다.

+0

David, 프로필에 오타가 있습니다. 'crytpo-currency'. – halfer

관련 문제