pthread_create() 에서 thread argument를 넘겨줄때...

idrukawa의 이미지

pthread_create() 에서 thread argument를 넘겨줄때 void* 형으로 넘겨주도록 되어 있는데요.
만약에 pthread_create를 호출하고 바로 종료되는 함수에서
그 함수의 지역변수를 인자로 넘겨주려고 하면 문제가 됩니다.
아래의 경우처럼요.

void* thr_func( void* Arg )
{
  char Buf[1024];
  strncpy( Buf, (char*)Arg, 1024 );
 
  printf( "Buf: %s", Buf );
 
  return NULL;
}
 
init_thr()
{
  char Tmp[]="test string";
 
  pthread_create( THR_IDX, 0, thr_func, (void*)Tmp );
  // sleep(1);
 
  return 0;
}

thr_func()에서 인자를 꺼내올 동안
init_thr()이 종료되지 안도록 sleep(1)을 주면 제대로 꺼내오는데
sleep(1)이 없으면 다른 데이터가 덮어써지는 경우가 있습니다.

sleep()은 임시 방편인것이고...
그렇다고 이 지역변수 char Tmp[]를 static으로 지정해주는것도 아닌것 같구요.
전역변수로 할바에는 인자로 넘겨줄 필요도 없구요.

적합한 해결방법이 무었인지 도움 요청합니다.

madman93의 이미지

#include <pthread.h>
#include <stdlib.h>
 
// 쓰레드 함수
void *test(void *data)
{
    int i;
    int a = *(int *)data;
    for (i = 0; i < 10; i++)
    {
        printf("%d\n", i*a);
    }
    return (void *)(i * 100);
}
 
int main()
{
    int a = 100;
    pthread_t thread_t;
    int status;
 
    // 쓰레드를 생성한다. 
    if (pthread_create(&thread_t, NULL, test, (void *)&a) < 0)
    {
        perror("thread create error:");
        exit(0);
    }
 
    // 쓰레드가 종료되기를 기다린후 
    // 쓰레드의 리턴값을 출력한다. 
    pthread_join(thread_t, (void **)&status);
    printf("Thread End %d\n", status);
    return 1;
}

---------------------------------------------
git init
git add .
git commit -am "project init"
---------------------------------------------

gilgil의 이미지

idrukawa의 이미지

제가 예제로 든 코드에서는 그렇게 안적었지만...
스레드함수(thr_func)는 실제 while로 동작하는 task입니다.
즉, 계속 무언가 자신의 작업을 수행하고 있는 녀석입니다.

init_thr()에서 pthread_join()을 쓰면 init_thr() 이 반환되지 않는 상태일 것입니다.
join은 main()에서 쓰고 있습니다.

즉 아래와 같은 구조라고 생각하시면 됩니다.

void* thr_func( void* Arg )
{
  char Buf[1024];
  strncpy( Buf, (char*)Arg, 1024 );
 
  printf( "Buf: %s", Buf );
 
  while(1)
  {
    ...
  }
 
  return NULL;
}
 
init_thr()
{
  char Tmp[]="test string";
 
  if( pthread_create( THR_IDX, 0, thr_func, (void*)Tmp ) < 0 )
  {
    return -1;
  }
  // sleep(1);
 
  return 0;
}
 
 
int main()
{
  if( init_thr() != 0 )
  {
    return -1;
  }
 
  if( init_thr2() != 0 )
  {
    return -1;
  }
 
  ... 
 
  pthread_join();
  pthread_join();
  ...
 
  return 0;
}

rgbi3307의 이미지

char Tmp[]="test string"; 을 main() 함수의 지역변수로 정의하고
Tmp를 init_thr()함수에 다시 전달하는 방법도 있을 수 있겠네요.

From:
*알지비 (메일: rgbi3307(at)nate.com)
*커널연구회(http://www.kernel.bz/) 내용물들을 만들고 있음.
*((공부해서 남을 주려면 남보다 더많이 연구해야함.))

익명 사용자의 이미지

주소를 인자로 넘기고 싶다면 지역변수의 주소값이 피하는건 당연해 보입니다.

문자열을 넘기고 싶다면 이렇게 하는건 어떨까요?

pthread_create(THR_IDX, 0, thr_func, (void *)"test string");

그리고, 인자 타입이 void * 이지만 값을 넘기고 싶다면 값을 넘기면 됩니다. 아래 처럼 말이죠.

#include <stdio.h>
#include <pthread.h> /* pthread_ */
#include <unistd.h> /* sleep */
 
void *
thr_func(void *Arg)
{
    fprintf(stdout, "%d\n", (int)Arg);
    fflush(stdout);
 
    return (void *)0;
}
 
int
init_thr(void)
{
    pthread_t th; 
    int i;
 
    i = 1234;
    pthread_create(&th, 0, thr_func, (void*)i);
 
    return 0;
}
 
int
main(int argc, char *argv[])
{
    init_thr();
 
    sleep(1);
    return 0;
}

gilgil의 이미지

thr_func 스레드 함수의 시작 부분에서 Tmp("test string") 값을 참조해야 하는데 init_thr 함수가 종료되면 Tmp 객체가 해제되기 때문에 발생하는 에러로 보이네요.

thr_func 함수에서 printf 코드가 실핼될 때까지는 Tmp 객체가 해제되지 않도록 event 처리를 해 주시기 바랍니다(mutex랑 wait condition 사용).

cinsk의 이미지

댓글 달기

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
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.