커맨드 라인 입력을 기반으로하는 스레드의 수인 멀티 스레드 프로그램을 작성하려고하므로 미리 선언 된 스레드를 하드 코딩 할 수 없습니다. 이것이 올바른 방법인가?n 개의 스레드를 생성하는 방법은 무엇입니까?
int threads = 5; // (dynamic, not hard-coded)
int i = 0;
pthread_t * thread = malloc(sizeof(pthread_t)*threads);
for (i = 0; i < threads; i++) {
pthread_t foobar;
thread[i] = foobar; // will this cause a conflict?
}
for (i = 0; i < threads; i++) {
int ret = pthread_create(&thread[i], NULL, (void *)&foobar_function, NULL);
if(ret != 0) {
printf ("Create pthread error!\n");
exit (1);
}
}
여기 아래에 제시 수정에서 내 결과입니다. 잘 작동하는 것 같습니다.
int threads = 5;
int i;
pthread_t * thread = malloc(sizeof(pthread_t)*threads);
for (i = 0; i < threads; i++) {
int ret = pthread_create(&thread[i], NULL, &foobar_function, NULL);
if(ret != 0) {
printf ("Create pthread error!\n");
exit (1);
}
// pthread_join(thread[i], NULL); // don't actually want this here :)
}
sleep(1); // main() will probably finish before your threads do,
free(thread); // so we'll sleep for illustrative purposes
int 쓰레드는 정수 쓰레드를 argth = argv [3] 비트에 할당 할 수 없다. 'atoi' 또는 sscanf –
을 사용해 주셔서 감사합니다. 맞습니다. 결정된. –
글쎄,'pthread_join()'이있는 곳에서 스레드를 생성하고 다음 스레드를 생성하기 전에 스레드가 끝날 때까지 기다려야합니다. 그래서 사실 당신은 여기에 준 단일 쓰레드 일 겁니다. –