我想将一个参数从 main() 传递到我的函数中。请让我知道我应该怎么做。我在网上看到了一些方法,但没有效果。 这是代码:
void *deliver(int *i)
{
int *ThreadID=(int *)tid;
//Here I would like to do some comparing on arrays using i parameter
//a[i]>b[i] As an example
}
void main ()
{
pthread_t t2_deliver[100];
//input var
printf("By using this code you can apply T threads on ordering list ;) \n");
printf("->*******************************************************************************<-\n");
printf("Please enter the number of threads(T):\n");
scanf("%d",&threadnum);
for (i=0; i<threadnum; i++)
{
pthread_create(&t2_deliver[i],NULL,deliver,&i);
}
最佳答案
您的代码中有逻辑错误。您创建的所有线程都将有一个指向相同 i
的指针,这意味着它将在所有线程中具有相同的值,并且很可能会超出线程的范围在创建线程的循环之后运行。
一种可能的解决方案是使用强制转换和标准 intptr_t
将值传递给线程函数:
pthread_create(..., (void*) (intptr_t) i);
在线程中:
void *deliver(int *p)
{
int i = (int) (intptr_t) p;
...
}
关于c - 如何将参数从线程传递到c中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42186990/