모든 자식 스레드가 완료될 때까지 메인 스레드를 대기시키는 방법은 무엇입니까?
나는 메인 스레드에서 2개의 스레드를 발사할 예정이며, 메인 스레드는 2개의 자식 스레드가 모두 끝날 때까지 기다려야 한다, 이렇게 합니다.
void *routine(void *arg)
{
sleep(3);
}
int main()
{
for (int i = 0; i < 2; i++) {
pthread_t tid;
pthread_create(&tid, NULL, routine, NULL);
pthread_join(&tid, NULL); //This function will block main thread, right?
}
}
위의 코드에서,pthread_join메인 스레드는 자식 스레드를 기다리지만 문제는 첫 번째 스레드가 끝날 때까지 두 번째 스레드가 생성되지 않는다는 것입니다.이건 제가 원하는 게 아닌데요.
제가 원하는 것은 2개의 스레드가 메인 스레드에 즉시 생성되고 메인 스레드가 완료될 때까지 기다리는 것입니다.처럼 보입니다.pthread_join속임수를 쓸 수는 없죠, 그렇죠?
아마도, 나는 생각했다, 나는 생각했습니다.semaphore제가 그 일을 할 수는 있지만, 다른 방법은 없나요?
int main()
{
pthread_t tid[2];
for (int i = 0; i < 2; i++) {
pthread_create(&tid[i], NULL, routine, NULL);
}
for (int i = 0; i < 2; i++)
pthread_join(tid[i], NULL);
return 0;
}
먼저 모든 스레드를 만든 다음 모든 스레드를 결합합니다.
pthread_t tid[2];
/// create all threads
for (int i = 0; i < 2; i++) {
pthread_create(&tid[i], NULL, routine, NULL);
}
/// wait all threads by joining them
for (int i = 0; i < 2; i++) {
pthread_join(tid[i], NULL);
}
아니면, 좀 드세요.pthread_attr_t변수에 pthread_attr_init(3)를 사용한 다음 pthread_attr_set detachedstate(3)를 사용한 다음 주소를 pthread_create(3) second 인수에 전달합니다.이렇게 하면 스레드가 분리된 상태로 생성됩니다.또는 사용pthread_detachJxh의 답변에 설명된 바와 같이.
좋은 Pthread 튜토리얼을 읽는 것을 기억하세요.음소거 및 조건 변수를 사용할 수 있습니다.
Qt나 POCO(C++로)와 같은 프레임워크를 사용하거나 좋은 C++ 책을 읽고 C++ 스레드를 사용할 수 있습니다.
개념적으로 스레드에는 각각의 콜 스택이 있으며 계속과 관련이 있습니다.그들은 "무겁다".
에이전트 지향 프로그래밍 접근 방식을 고려해 보십시오. 경험상 많은 스레드를 원하지 않습니다(예: 10개의 코어 프로세서에 20개의 스레드가 있는 것이 합리적입니다.200개의 스레드는 대부분의 스레드가 절전 또는 대기 상태가 아니면 실행되지 않습니다. 또한 스레드가 뮤텍스 및 조건 변수를 사용하여 동기화되고 다른 스레드와 통신 및/또는 동기화되기를 원합니다(초당 204회).스레드 간의 다른 통신 방법으로 poll(2), fifo(7), unix(7), sem_overview(7) 및 shm_overview(7)를 참조하십시오.일반적으로 신호(7)를 스레드와 함께 사용하지 않도록 하고(신호 안전(7)... 읽기) dlopen(3)을 주의하여 사용합니다(아마 메인 스레드에서만 사용할 것).
실용적인 접근 방식은 대부분의 스레드가 일부 이벤트 루프(poll(2), pselect(2), eventfd(2), signald(2), ...)를 실행하고 파이프(7) 또는 unix(7) 소켓을 사용하여 통신하는 것입니다.소켓(7)을 참조하십시오.
스레드 간의 통신 프로토콜을 문서화하는 것을 잊지 마십시오.이론적인 접근을 위해서, γ-calculus에 관한 책을 읽고 동시 프로그램을 디버깅하는 것은 어렵다는 라이스의 정리를 알아두세요.
스레드를 분리하여 시작할 수 있으며, 참여할 걱정이 없습니다.
for (int i = 0; i < 2; i++) {
pthread_t tid;
pthread_create(&tid, NULL, routine, NULL);
pthread_detach(tid);
}
pthread_exit(0);
또는 다이가 생성된 스레드를 주 스레드로 다시 보고하도록 하여 스레드가 생성된 순서가 아닌 종료된 순서로 결합되도록 할 수 있습니다.
void *routine(void *arg)
{
int *fds = (int *)arg;
pthread_t t = pthread_self();
usleep((rand()/(1.0 + RAND_MAX)) * 1000000);
write(fds[1], &t, sizeof(t));
}
int main()
{
int fds[2];
srand(time(0));
pipe(fds);
for (int i = 0; i < 2; i++) {
pthread_t tid;
pthread_create(&tid, NULL, routine, fds);
printf("created: %llu\n", (unsigned long long)tid);
}
for (int i = 0; i < 2; i++) {
pthread_t tid;
read(fds[0], &tid, sizeof(tid));
printf("joining: %llu\n", (unsigned long long)tid);
pthread_join(tid, 0);
}
pthread_exit(0);
}
#include<stdio.h>
#include<pthread.h>
int icnt = 0; //in non_bss data segment
pthread_mutex_t lock; //lock variable created stored into bss data segment
void *Thread_count(void* args) //syncronization
{
pthread_mutex_lock(&lock); //lock aquire
icnt++;
for(int x = 1; x <= icnt; x++)
{
printf("Hello from Thread_count : %d \n",icnt);
}
printf("\n");
pthread_mutex_unlock(&lock); //release lock
pthread_exit(NULL); //exit from child thread
}
int main()
{
pthread_t threads[4]; //created array of {unsigned long int}
int status = 0;
//creating threads in loop
for(int i = 1; i <= sizeof(threads)/sizeof(threads[0]); i++)
{
pthread_create(&threads[i], NULL, &Thread_count, NULL);
}
//waiting for threads in loop
for(int j = 1; j <= sizeof(threads)/sizeof(threads[0]); j++)
{
pthread_join(threads[j], &status);
printf("Thread number : %d <--> Thread status : %d\n",j, status);
}
pthread_exit(0); //end of main thread
}
언급URL : https://stackoverflow.com/questions/11624545/how-to-make-main-thread-wait-for-all-child-threads-finish
'programing' 카테고리의 다른 글
| 그룹의 행 번호 증분 (0) | 2023.06.26 |
|---|---|
| Oracle 10g에서 문자열 날짜를 날짜 형식으로 변환하는 방법 (0) | 2023.06.26 |
| 열의 값을 기존 데이터 프레임의 행 이름으로 변환 (0) | 2023.06.26 |
| 주변 선언이란 무엇입니까? (0) | 2023.06.26 |
| 느낌표가 루비 방식에 사용되는 이유는 무엇입니까? (0) | 2023.06.26 |