所以我有这个
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/