this 및 this 게시물을 stackoverflow에 게시했지만 그 중 아무도 내가 원하는 것을 제공하지 않습니다.블로킹 스레드 없음
필자의 경우 스레드를 생성하고 실행하고 주 프로세스가 실행되는 동안 차단 통계없이 실행하려고합니다. 이 스레드는 통신이 없으며 주 프로세스와 동기화되지 않으며 완전히 독립적으로 작업을 수행합니다.
이 코드를 고려하십시오
#define DAY_PERIOD 86400 /* 3600*24 seconds */
int main() {
char wDir[255] = "/path/to/log/files";
compress_logfiles(wDir);
// do other things, this things let the main process runs all the time.
// just segmentation fault, stackoverflow, memory overwrite or
// somethings like that stop it.
return 0;
}
/* Create and launch thread */
void compress_logfiles(char *wDir)
{
pthread_t compressfiles_th;
if (pthread_create(&compressfiles_th, NULL, compress, wDir))
{
fprintf(stderr, "Error create compressfiles thread\n");
return;
}
if (pthread_join(compressfiles_th, NULL))
{
//fprintf(stderr, "Error joining thread\n");
return;
}
return;
}
void *compress(void *wDir)
{
while(1)
{
// Do job to compress files
// and sleep for one day
sleep(DAY_PERIOD); /* sleep one day*/
}
return NULL;
}
에서 compress_logfiles 기능 ptheard_join 와를 스레드가 성공적으로 모든 파일을 압축 결코 그것이 무한 while 루프에 있기 때문에 반환, 그래서 주요 과정은 여전히 모든 차단 시각. 내가에서 compress_logfiles ptheard_join 기능을 을 제거하면이 스레드 수익을 기다리지 않기 때문에, 주요 프로세스가 차단되지 않지만, 스레드는 (하나의 haundred을 arround, 거기에 많은 파일) 하나의 파일 종료를 압축합니다.
그래서 메인 프로세스가 compressfiles_th 스레드를 시작하고 종료 또는 종료를 기다리지 않고 자신의 일을하게하는 방법이 있습니까? 내가 Linux Programmer's Manual에 pthread_tryjoin_np 및 pthread_timedjoin_np을 발견, 그것이 내가 반환 값의 상관하지 않는 경우 pthread_tryjoin_np 일을 할 것 같다, 그것을 사용하는 것이 좋습니다?
감사합니다.
편집 1 :은
메인 프로세스가 compress_logfiles (wDir)을 호출 한 후 daemonized되어 있습니다, 아마도 daemonization는이 문제-출시 다시 메인 프로세스를 종료하고?
편집 2 :
예, 포크가 문제를 일으키는
신용 dbush 에 솔루션 및 그것을 해결() pthread_atfork 명령. 기능이 포크 후()를 호출
#define DAY_PERIOD 86400 /* 3600*24 seconds */
char wDir[255] = "/path/to/log/files"; // global now
// function added
void child_handler(){
compress_logfiles(wDir); // wDir is global variable now
}
int main()
{
pthread_atfork(NULL, NULL, child_handler);
// Daemonize the process.
becomeDaemon(BD_NO_CHDIR & BD_NO_CLOSE_FILES & BD_NO_REOPEN_STD_FDS & BD_NO_UMASK0 & BD_MAX_CLOSE);
// do other things, this things let the main process runs all the time.
// just segmentation fault, stackoverflow, memory overwrite or
// somethings like that stop it.
return 0;
}
child_handler : 나는 주 과정을 차단하지 않고 compressfiles_th를 실행하려면이 변화했다.
위 코드는 설명하는 동작을 나타냅니다. 'pthread_join'에 대한 호출을 주석 처리하면 스레드 함수가 종료되지 않습니다. 질문을 [최소, 완전하고 검증 가능한 예] (http://stackoverflow.com/help/mcve)로 업데이트하십시오. – dbush
dbush 내 편집보기 – Phiber
pthread_join() 호출을 main()의 맨 아래로 옮겨서 주 스레드가 종료 준비가 될 때까지 원하는대로 자유롭게 할 것을 제안합니다. (이 시점에서 pthread_join()을 호출하여 main()이 반환되기 전에 compress-thread가 종료되었는지 확인하여 압축 스레드와 프로세스 정리 사이에 잠재적 인 경쟁 조건이 발생하지 않도록해야합니다. 물론 그 시점에서 압축 스레드를 종료하는 일부 메커니즘, 예를 들어 압축 스레드가 주기적으로 검사하는 원자 변수를 설정하는 것만으로도 충분합니다.) –