【问题标题】:C Pass the Parent-Thread IDC 传递父线程 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);
}

【问题讨论】:

    标签: c linux multithreading arguments pthreads


    【解决方案1】:

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

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 2021-12-17
    • 2012-02-18
    • 2011-08-04
    • 2012-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多