c - 如何将参数从线程传递到c中的函数

标签 c multithreading pthreads

我想将一个参数从 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/

相关文章:

c - 使用 libzip 解压一个文件

c - LNK 2001 : Unresolve external symbol struct **

Android:无法关闭进度对话框

c - 如何让多个 POSIX 线程等待另一个线程开始

c - pthread条件变量和mutex,程序出现死锁

c: 如何将 strtok() 用于双括号?

c - open62541 客户端断开连接时 OPC UA 堆栈服务器端回调

c# - 我怎样才能同步这两个线程?

c - 等待所有线程计时器回调完成的安全方法

c - 在随机条件下的无限 while 循环中创建读取器和写入器线程时出现段错误