在 C 语言的后台运行线程

running threads in background in c

本文关键字:运行 线程 后台 语言      更新时间:2023-10-16

我用pthread_create创建了5个线程。我想在后台运行这些线程,所以我没有加入这些线程。但是该程序正在产生奇怪的输出。这些原因可能是什么?

程序:

for(i = 0; i < 5; i++)
{
pthread_create(&thread[i], NULL, func, &i)
}

一个可能的原因可能是您将指向i的指针作为参数传递给线程,并且该指针对于所有线程都是相同的。因此,在循环之后,将为所有线程5 i


您可以使用正确的类型转换将实际值作为指针传递,而不是传递指针:

pthread_create(&thread[i], NULL, func, (void *) i);

在线程函数中:

void *func(void *thread_argument)
{
    int i = (int) thread_argument;
    /* ... */
}