0

刚刚遇到一个关于如何将第四个参数传递给 pthread_create() 的奇怪问题。

原来,我写的代码如下:

auditLogEntry *newEntry = NULL;

// malloc and init the memory for newEntry
rc = audit_init_log_entry(&newEntry);
// wrapper of 'goto cleanup'
ERR_IF( rc != 0 );
...
rc2 = pthread_attr_init(&attr);
ERR_IF( rc2 != 0 );
rc2 = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
ERR_IF( rc2 != 0 );
rc2 = pthread_create(&syslog_thread, &attr, syslog_thread_handler, (void *)newEntry);
ERR_IF( rc2 != 0 );
newEntry = NULL;
...
cleanup:
pthread_attr_destroy(&attr);
if (newEntry != NULL)
{
    audit_free_log_entry(newEntry);
    newEntry = NULL;
}

static void *syslog_thread_handler(void *t)
{
    auditLogEntry *entry = (auditLogEntry *)t;
    ... // code using entry
    cleanup:
    audit_free_log_entry(entry);

    pthread_exit(0);
}

一切正常。

然后,我做了一个改变:

rc2 = pthread_create(&syslog_thread, &attr, syslog_thread_handler, (void *)&newEntry);
ERR_IF( rc2 != 0 );
...
cleanup:
pthread_attr_destroy(&attr);
if (rc != 0 && newEntry != NULL)
{
    audit_free_log_entry(newEntry);
    newEntry = NULL;
}

static void *syslog_thread_handler(void *t)
{
    auditLogEntry **entry = (auditLogEntry **)t;
    ... // code using *entry
    cleanup:
    audit_free_log_entry(*entry);
    *entry = NULL;

    pthread_exit(0);
}

在上述更改之后,线程处理程序将使用 *entry 来访问日志条目数据。但它没有用。更糟糕的是,进程核心被转储了。

我尝试了“man pthread_create”,但没有特别提到应该如何将最后一个参数传递给它。

我这里有什么错吗?

4

2 回答 2

2

您没有显示完整的代码,因此很难判断发生了什么。

但是,&newEntry为您提供了指向堆栈上变量的指针。如果newEntry超出范围,例如因为您的函数结束,您的另一个线程现在有一个无效的指针 - 指向堆栈上现在已经消失的位置。并且取消引用这样的指针会导致未定义的行为。

int *foo(void) 
{
   int x = 2;
   return &x;
}

void bar(void)
{
   int *x = foo();
   printf("%d\n", *x); //can't do this, x points to something
                       //on the stack in the foo function, 
                       //which isn't valid any more
}

如果将 foo() 函数传递&x给它创建的线程,您将遇到同样的问题。

void foo(void) 
{
   int x = 2;
  ...
  pthread_create(&tid, bar, NULL, &x);
}

void *bar(void *arg) { int *x = arg;

   printf("%d\n", *x); //same problem here, x points to something
                       //on the stack in the foo function, which isn't valid 
                       //if the foo function ends. This concept is exactly the same
                       //if x had been a pointer inside the foo() function.
}

这可能是您的情况:

int globalx = 2; //global variable
void foo(void) 
{
  int *x = malloc(sizeof(int));
  ...

  pthread_create(&tid, bar, NULL, &x); //we're still taking the address of 
                                       //a local variable. 
}

void *bar(void *arg) 
{
   int **x = arg;
   printf("%p\n", *x); //still the same problem here, x points to something
                       //on the stack in the foo function, which isn't valid 
}
于 2012-08-08T21:48:15.790 回答
0

无论核心转储来自何处,都不是来自 pthreads。你对最后一个论点所做的事情绝对没问题。

于 2012-08-08T21:43:00.593 回答