c - 分离线程 : Handler not showing the Printfs

标签 c linux pthreads

<分区>

我尝试在 C Linux 中使用 Detached Threads 编译和运行以下代码。问题是我希望每个线程都向我显示来自处理程序 *idThreadMethod 的相应 printf,但它没有向我显示任何内容!我尝试在调用 pthread_create 函数之前使用 printf 并显示它,但问题应该在 *idThreadMethod(处理函数)中。代码:

//gcc detachedThreads.c -lpthread -o p
//./p 4

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int i;

void *idThreadMethod(void *args)
{
    int pid;

    pid = *((int *)args);

    printf("\nI'm The Detached Thread %d\n", i);
    printf("\nMy PID is: %d\n", pid);

    pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
    int quantityThreads, returnThread, pid;
    pthread_t idThread[15];
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);

    if(argc-1 < 1)
    {
        printf("\nSome arguments are missing\n");
        return EXIT_FAILURE;
    }

    quantityThreads = atoi(argv[1]);

    pid=getpid();
    int *it = &pid;

    for(i=0;i<quantityThreads;i++)
    {
        returnThread = pthread_create(&idThread[i],&attr,idThreadMethod,it);

        if(returnThread == -1)
        {
            printf("\nThere is an error trying to create the thread\n");
            return EXIT_FAILURE;
        }
    }                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    return EXIT_SUCCESS;
}

我该怎么做才能显示来自 *idThreadMethod 函数的 printf 消息?

最佳答案

在 main 中,使用 pthread_exit。您的 main 正在退出,因此您的其余线程将终止,无论是否分离。

关于c - 分离线程 : Handler not showing the Printfs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19129274/

相关文章:

c - 返回指向数组的指针的函数中的段错误

c++ - glibc 在 RHEL 5 中损坏了双链表

c - PThreads:内核与线程

c - 将多个值返回到C中的线程时出错

c - POSIX API 调用以列出进程中运行的所有 pthreads

c - 在 Visual Studio 中编写 C 代码

c - "How much memory space does an array takes if the maximum size that is declared is not used?"

c - qsort const指针问题

linux - 如何使用 find + grep + sed + xargs 或其他方式批量重命名文件

c++ - 编译 qt 项目给 operator delete(void*, unsigned int) undefined reference