특정 메서드가 호출 될 때마다 새 스레드를 만드는 프로그램을 만들고 싶습니다. 여기까지 내 작업 코드는 다음과 같습니다.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"스레드가 완료되면 자체 스레드가 고아 프로세스로 남은 후에 정리하지 않습니다.
내가 가진 한 가지 아이디어는 벡터를 사용하여 각 스레드 번호를 추적 한 다음 주 끝에서 최종 결합에 사용하는 것이 었습니다. 그러나 그 문제는 어레이 목록이 쉽게 커질 수 있으며 스레드가 완료 되더라도 축소되지 않는다는 것입니다.
David, 프로필에 오타가 있습니다. 'crytpo-currency'. – halfer