gpt4 book ai didi

c - 卡在线程问题上

转载 作者:太空宇宙 更新时间:2023-11-04 03:55:57 25 4
gpt4 key购买 nike

所以我有这个

void* tf(void* p);

我完全不明白。我认为它是一个带有参数空指针的函数指针。我正在使用它制作这样的线程:

pthread_create( &thread_id[i], NULL, tf, NULL );

我需要的是 tf 的解释以及如何将参数传递给它。

我将函数定义为

void* tf(void* p) 
{
//I would like to use p here but dont know how.
}

这个函数在 main 之外,需要获取一些在 main 内部设置的其他参数。我试过让它看起来像这样 tf(int i) 但我遇到了段错误。所以我知道我做错了什么,需要一些帮助来解决。

感谢您对此问题的任何帮助。

杰森

最佳答案

pthread_create( &thread_id[i], NULL, tf, NULL );
// ^^^^^
// You have to put here the pointer (address) to your data

然后你可以从p指针获取你的数据到线程函数中

例子

typedef struct test {
int a,b;
} test;

int main()
{
struct test T = {0};
pthread_create( &thread_id[i], NULL, tf, &T );
pthread_join(thread_id[i], NULL); // waiting the thread finish
printf("%d %d\n",T.a, T.b);
}

void* tf(void* p)
{
struct test *t = (struct test *) p;
t->a = 5;
t->b = 4;
}

关于c - 卡在线程问题上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16442398/

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