gpt4 book ai didi

正确使用 POSIX 的 pthread_exit 和 pthread_join

转载 作者:太空宇宙 更新时间:2023-11-04 01:08:33 24 4
gpt4 key购买 nike

我正在尝试了解从 pthread 返回值并捕获该值的概念,但我不明白发生了什么,也不知道如何让它工作。我有一个创建单个线程的简单程序,该线程以 int 值 100 退出,然后我尝试使用 pthread_join 捕获该值:

#include <stdio.h>
#include <pthread.h>

void *doStuff(void *param) {
int a = 100;
pthread_exit(a);
}

void main() {
pthread_t thread;
int a;
pthread_create(&thread, NULL, doStuff, NULL);
pthread_join(thread, &a);
printf("%d\n", a);
}

它有效,但会发出一些警告:

./teste.c: In function ‘doStuff’:
./teste.c:7:2: warning: passing argument 1 of ‘pthread_exit’ makes pointer from integer without a cast [enabled by default]
In file included from ./teste.c:2:0:
/usr/include/pthread.h:241:13: note: expected ‘void *’ but argument is of type ‘int’
./teste.c: In function ‘main’:
./teste.c:17:2: warning: passing argument 2 of ‘pthread_join’ from incompatible pointer type [enabled by default]
In file included from ./teste.c:2:0:
/usr/include/pthread.h:249:12: note: expected ‘void **’ but argument is of type ‘int *’

我不明白为什么我会收到这些警告,老实说我也不明白为什么这会起作用,因为我认为我必须在 pthread_exit 上返回一个空指针。

这是一个简单的示例,我正在努力开始工作,以便能够完成我正在尝试创建的另一个程序,在该程序中我将有一个线程数组,每个线程都计算一个单个浮点值,我想使用 pthread_exit 和 pthread_join 将每个计算值存储到 float 组中,但我真的不知道如何将 pthread_join 中的值存储到数组中。

最佳答案

pthread_exit 采用 void*,而不是 int。 (请注意,调用 pthread_exit(x) 与简单地从线程函数返回 x 是一样的。)

解决您的问题的最简单方法是向线程函数传递一个指向 int 的指针,在其中存储生成的值:

void *doStuff(void *param) {
int a = 100;
*(int*)param = a;
return NULL;
}

int main(void) {
pthread_t thread;
int a;
pthread_create(&thread, NULL, doStuff, &a);
pthread_join(thread, NULL);
printf("%d\n", a);
}

编辑:如果您真的需要使用线程函数的返回值来传达结果,您有几个选择。

(1) 将返回值转换为void*:

void *doStuff(void *param) {
int a = 100;
return (void*)a;
}

int main(void) {
pthread_t thread;
pthread_create(&thread, NULL, doStuff, NULL);
void* ptr;
pthread_join(thread, &ptr);
int a = (int)ptr;
printf("%d\n", a);
}

这感觉有点老套,因为确实如此。如果您确定在 void* 之间来回转换将在您将要定位的每个平台上保留 int 的值,那么一定要放弃。

(2) 返回指向包含返回值的动态分配存储的指针:

void *doStuff(void *param) {
int a = 100;
int* ptr = malloc(sizeof(*ptr));
assert(ptr); /* I'm lazy, sue me. */
*ptr = a;
return ptr;
}

int main(void) {
pthread_t thread;
pthread_create(&thread, NULL, doStuff, NULL);
void* ptr;
pthread_join(thread, &ptr);
int a = *(int*)ptr;
free(ptr);
printf("%d\n", a);
}

(3) 制作一个结构来封装线程的所有输入/输出参数(重量级,但非常明确):

struct foo {
int input1;
int input2;
int result;
};

void *doStuff(void *param) {
foo* f = param;
f->result = f->input1 + f->input2;
return NULL;
}

int main(void) {
foo* ptr = malloc(sizeof(*ptr));
assert(ptr);
ptr->input1 = 5;
ptr->input2 = 3;

pthread_t thread;
pthread_create(&thread, NULL, doStuff, ptr);
pthread_join(thread, NULL);

printf("%d\n", ptr->result);
free(ptr);
}

关于正确使用 POSIX 的 pthread_exit 和 pthread_join,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18153244/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com