3

我有以下内容:

void *Thrd(void *data)
{
    int ret;
    ret = myfunc();
    pthread_exit((void *)ret);
}

int main(int argc, char *argv[])
{
    int status;

    pthread_create(&Thread, NULL, Thrd, &data);

    pthread_join(txThread, (void **)&status);
    if (status)
        printf("*** thread failed with error %d\n", status);
}

它可以工作,我可以读取状态,但我在编译时收到以下警告:

test.cpp: In function ‘void* Thrd(void*)’:
test.cpp:468:26: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]

这是与pthread_exit()

我根本找不到问题所在:( ...

4

3 回答 3

3

因此,您正试图从线程函数返回一个整数值。POSIX 线程函数只能返回void*.

有几种方法可以从另一个线程返回值:

1)您可以void*来回转换一个整数,只要void*足够宽以保持该值而不会被截断:

void *Thrd(void *vdata) {
    int value = ...;
    void* thread_return_value = (void*)value;
    return thread_return_value;
}
// ...
void* status;
pthread_join(txThread, &status);
int value = (int)status;

2) 将返回值的地址传递给线程函数并让线程函数设置该值:

struct Data { int return_value; };

void *Thrd(void *vdata) {
    // ...
    int value = ...;
    struct Data* data = vdata;
    data->return_value = value;
    return NULL;
}
// ...
pthread_create(&Thread, NULL, Thrd, &data);
pthread_join(txThread, NULL);
int value = data->return_value;

3)让线程分配返回值。join() 的另一个线程需要读取该值并释放它:

void *Thrd(void *vdata) {
    // ...
    int* value = malloc(sizeof *value);
    *value = ...;
    return value;
}
// ...
void* status;
pthread_join(txThread, &status);
int* value = status;
// ...
free(value);
于 2012-12-19T10:11:59.177 回答
0

而不是这个:

pthread_exit((void *)ret);

写这个:

pthread_exit((void *)&ret);

在“pthread_exit((void *)ret)”中,您告诉pthread_exit在 address 有一个返回值pertaining to the value contained in ret variable。您希望将结果存储在 ret 的地址,所以它应该是pthread_exit(&ret).

Nowret是一个局部整数变量。如果你写:

int *ret=malloc(sizeof(int));

if(ret==NULL)

  //handle the error

*ret=func();

pthread_exit(ret);

并且不要忘记free指针。

于 2012-12-19T09:47:59.543 回答
0

您正在将非指针转换为指针 - 这可能就是您收到警告的原因。也许您可以修改代码以使用 aint*而不是您的int ret,并将其转换为void*.

编辑:正如托尼狮子所说。

于 2012-12-19T09:53:12.940 回答