如何等待线程完成工作,其中克隆是在c中创建的?

问题描述 投票:0回答:1

我尝试等待main函数,直到线程完成其工作。但是主要功能完成其工作并退出。我认为是因为线程在变量中没有正确的指针/值。(计数和步骤)

有人知道在这种情况下如何正确使用waitpid / wait吗?

我的代码:

#define _GNU_SOURCE
#include <stdio.h>
#include <inttypes.h> /* for PRIu64 and uint64_t */
/* you'll need further includes */
#include <sched.h>
#include <stdlib.h>
#include "tally.h"
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define STACK_SIZE 32768
#define THREADS 2
struct clone_args{
        uint64_t steps;
        uint64_t* tally;

};
int incHelper(void* arg){
        struct clone_args *args = (struct clone_args*)arg;
        uint64_t steps= args->steps;
        uint64_t* tally = args->tally;
        increment(tally,steps);
        (void) arg;
        (void) tally;
        (void) steps;
        exit(2);
        return 0;
}

int main ()
{
        uint64_t N = 10000000;
        uint64_t tally = 1;
        tally_init();
        int thread_pid[THREADS];
        int status;
        for(int i= 0; i<THREADS;i++){
                void *child_stack = malloc(STACK_SIZE);
                struct clone_args *arguments = malloc(sizeof(struct clone_args));
                arguments->steps = N;
                arguments->tally = &tally;
                void* arg = (void*) &arguments;
                thread_pid[i] = clone(incHelper, child_stack+STACK_SIZE,CLONE_VM, arg);
                pid_t pid = waitpid(thread_pid[i],&status,SIGCHLD);
                printf("C-PID [%d]\n", thread_pid[i]);
                (void) pid;
        }

        tally_clean();
        printf( "\nTally is %" PRIu64 "\n", tally );
        (void) N;
        (void) thread_pid;
        (void) tally;
        (void) status;
        printf("\n MAIN PROGRAMM END\n");
        return 0;
}

增量功能:

/* modify this function to achieve correct parallel incrementation */
void  increment ( uint64_t *tally, uint64_t steps )
{
        printf("\nTALLY: %"PRIu64"\n",*tally);
        printf("STEPS: %"PRIu64"\n",steps);
        for( uint64_t i = 0; i < steps; i++ )
        {
                *tally += 1;
        }
        return;

}

运行代码后得到的结果:

C-PID [29819]
C-PID [29820]

Tally is 1

 MAIN PROGRAMM END
root@...(~/Downloads/asst3/asst3-clone)$
TALLY: 0
STEPS: 140714329004032

TALLY: 888309
STEPS: 140714329004032

代码应使用两个线程递增变量。为了避免临界区问题,我应该使用信号灯。但这是另一项练习。首先练习使用clone()函数创建两个线程。我不明白,如果clone()的标志错误或我的代码完全错误。我是C语言的新手。

我花了最后12个小时在Google上搜索。

我感谢您的每一个回答:)。

对不起,英语不好。

问候

c multithreading wait waitpid
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.