C 传递父线程 ID

Posted

技术标签:

【中文标题】C 传递父线程 ID【英文标题】:C Pass the Parent-Thread ID 【发布时间】:2021-12-31 22:28:21 【问题描述】:

如何传递父 ID 并在第二个 printf() 中打印出来??

第一行示例:

我 1 岁,我有 4 个孩子(dren)我的父母 ??? 我 2 岁,我有 2 个孩子(dren)我的父母???

预期: 我是 1,我有 4 个孩子(dren)我的父母 0 我 2 岁,我有 2 个孩子(dren)我的父母 1

#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>


typedef struct parameter 
    unsigned int amount_children;
    int thread_number;
 parameter_t;

#define MAX_CHILDTHREADS 16
#define N_ZERO 4
unsigned int countthreads = 0;
unsigned int divisor = 2;

pthread_mutex_t count_mutex;
pthread_attr_t attr;



void * tree(void*);

int main()
    pthread_t th;
    pthread_attr_init(&attr);
    pthread_mutex_init(&count_mutex,NULL);
    //countthreads++;
    parameter_t params =  N_ZERO*divisor, countthreads;
    //pthread_create(&th,&attr,&tree,(void*)&params);
    tree(&params);
    printf("Totalamount of created Threads %d \n", countthreads);



void * tree(void * args)
    parameter_t* paramArgs = (parameter_t*) args;
    int N_threads = paramArgs->amount_children / divisor; // anzahl der theoretisch benötogten Threads
    int amount_childthreads = (N_threads <= MAX_CHILDTHREADS) ? N_threads : MAX_CHILDTHREADS;
    pthread_t threads[amount_childthreads];
    printf("I am %d and and I have %d child(dren), my parent is ???\n", paramArgs->thread_number, 
    amount_childthreads);

    parameter_t param[ amount_childthreads ];
    for(int i = 0; i < amount_childthreads; i++)
        pthread_mutex_lock( &count_mutex );
        int j = ++countthreads;
        pthread_mutex_unlock( &count_mutex );

        param[i].amount_children = N_threads;
        param[i].thread_number = j;
        pthread_create( threads+i, &attr, &tree, param + i );
    

    for(int i = 0; i < amount_childthreads; i++)
        pthread_join(threads[i],NULL);
    
    printf("I am %d and done\n",paramArgs->thread_number);

【问题讨论】:

【参考方案1】:

您可以使用 POSIX getppid() 函数来获取父进程的 PID。

【讨论】:

正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center。

以上是关于C 传递父线程 ID的主要内容,如果未能解决你的问题,请参考以下文章

多个进程之间的消息传递,每个进程在 c 中有许多线程

如何重用线程 - pthreads c

是否有任何 linux 函数调用通过传递线程 ID 来获取特定线程的 CPU 使用率?

C++11多线程第三篇:线程传参详解,detach()大坑,成员函数做线程参数

C++11多线程第三篇:线程传参详解,detach()大坑,成员函数做线程参数

父子线程和线程池如何实现threadLocal变量传递