timer와 일정주기로 드는 thread 비교

삼구의신의 이미지

일반적으로 timer를 검색하면 나오는 signal handler를 이용해 설정한 interval 마다
signal을 발생시키고 handler에 등록된 동작하도록하는 타이머와.
쓰레드에서 usleep과 같은 것을 넣어 일정 주기마다 쓰레드가 돌도록 동작하느것 둘이 어느 차이가 있나요?

timer code

	struct sigaction sa;
    struct itimerval timer;
 
   // Install timer_handler as the signal handler for SIGVTALRM. 
    memset (&sa, 0, sizeof (sa));
    sa.sa_handler = timer_handler_wrapper;
    sigaction (SIGVTALRM, &sa, NULL);
 
//     Configure the timer to expire after 1 sec... 
    timer.it_value.tv_sec = 1;
    timer.it_value.tv_usec = 0;
 
//     ... and every 50 msec after that. 
    timer.it_interval.tv_sec = 0;
    timer.it_interval.tv_usec = TIMER_INTERVAL;
 
//     Start a virtual timer. It counts down whenever this process is executing. 
    setitimer(ITIMER_VIRTUAL, &timer, NULL);
 
//     Do busy work.  
 
	while(1){
		};

thread 코드

int run()
{
 while(1)
 {
   // something
   usleep(50000);
 }
}
jick의 이미지

쓰레드를 쓸 수 있는 상황이라면 쓰레드가 훨씬 편합니다. 일단 쓰레드에서는 printf도 되고 vector도 되고 웬만한 함수는 거의 다 됩니다.

Signal handler에서는 웬만한 건 다 안됩니다.

게다가 이전 질문을 보니 이미 멀티쓰레드를 사용중이신 것 같은데, 멀티쓰레드 상황에서 시그널을 쓰는 건 지뢰밭이라 대단히 공부하지 않으면 제대로 쓰기 힘듭니다. (일단 시그널이란 놈이 쓰레드 이전에 만들어진 개념이라, 일반적으로 시그널이 떴을 때 어느 쓰레드가 받을지 보장이 안됩니다.)

* 그나저나 위의 코드처럼 적으면 "something"을 할 때 계속 시간이 흐르고 있기 때문에, 정확히 50ms마다 뭘 한다는 보장이 안됩니다. (something에 40ms가 걸릴 경우를 생각해 보면 명확하죠.) 뭐 원래 의도가 뭐였냐에 따라 상관없을 수도 있는데, 더 정확한 타이머가 필요하다면 시작할 때 현재 시간을 기억해 놓고 매번 "다음번에 깨어나야 할 시간"을 계산해서 그만큼 sleep을 하는 게 좋습니다.

삼구의신의 이미지

마지막에 말씀하신 정확한 타이머를 쓰기위해선
다음번에 깨어나야할 시간을 계산해서 sleep을 준다는말을 이해못하겠어요 ㅠㅠ
조금만더 자세히 설명해주실수 있을까요?

yhsuk의 이미지

대신 슈도코드로 예를 들어 드리면, 이런 식입니다.

void *thread_run(void *)
{
    while(1)
    {
        stime = clock_gettime(....);
        // something
        etime = clock_gettime(....);
 
        elapse_time = etime - stime; // elapsed_time은 somethine을 수행하는 데 걸린 시간
        usleep(50000 - elapsed_time);
    }
}

Signature :) - "여유를 갖고 행동하되 게을러지지 말자"

yhsuk의 이미지

위에 소요시간에 대해서 따로 계산하여 적용하는 방법 외에,
타이머 관련해서는 리눅스 플랫폼에서만 사용가능한 timerfd_create, timerfd_settime도 있습니다.

Signature :) - "여유를 갖고 행동하되 게을러지지 말자"

삼구의신의 이미지

공부해봐야겠네요 ㅎㅎㅎ

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.