簡體   English   中英

使用 fork (process) 而不是 pthread 來實現相同的

[英]use fork (process) instead of pthread to acieve the same

我通過創建並行線程實現了以下代碼的並發性。 但是,我應該如何使用 fork() 創建子進程並執行與下面的 main() 相同的工作? 我想避免創建任何線程。

struct function_args
    {
        pthread_t thread;
        char *command;
    };
    
    int main()
    {
        while (1)
            {
                if (mode == 1)
                    printf("$> ");
    
                if ((nread = getline(&line, &linecap, in)) > 0)
                {
                    char *command;
                    int commands_num = 0;
                    struct function_args args[BUFF_SIZE];
    
                    // remove newline character
                    if (line[nread - 1] == '\n')
                        line[nread - 1] = '\0';
    
                    char *temp = line;
    
                    while ((command = strsep(&temp, "&")) != NULL)
                        if (command[0] != '\0')
                        {
                            args[commands_num++].command = strdup(command);
                            if (commands_num >= BUFF_SIZE)
                                break;
                        }
    
                    for (size_t i = 0; i < commands_num; i++)
                        if (pthread_create(&args[i].thread, NULL, &parseInput, &args[i]) != 0)
                            printError();
    
                    for (size_t i = 0; i < commands_num; i++)
                    {
                        if (pthread_join(args[i].thread, NULL) != 0)
                            printError();
                        if (args[i].command != NULL)
                            free(args[i].command);
                    }
                }
                else if (feof(in) != 0)
                {
                    atexit(clean);
                    exit(EXIT_SUCCESS);    // EOF
                }
            }
    
            return 0;
    }

我知道pid = fork()返回一個 processid,對於孩子來說它是 0,對於父母來說是 >0。 但是,在下面我處理多個argv的 for 循環中,我不確定如何翻譯我的 main() 來這樣做。

這真的取決於你在做什么。 一般來說,您可以執行以下操作:

for (size_t i = 0; i < commands_num; i++)
{
    pid_t pid = fork();
    if (pid == 0)
    {
        parseInput(&args[i]);
        exit(0);
    }
    else if (pid == -1)
        printError();
    else
        args[i].thread = pid;
}

子進程獨立於父進程和 go 來完成他們的任務,因此可能不需要在此處執行等效於pthread_join()的操作,在這種情況下將是waitpid() ,除非父進程必須等待他們的產品用它做點什么。

說到這一點,一旦進程被分叉,它們就不再共享相同的 memory 空間,因此在子進程和父進程之間傳輸信息本身可能是一個挑戰。 如果您只是將內容打印到stdout ,則設置為 go,否則您必須找出管道以使父子通信。

使用系統本機線程(或特別是 pthreads)的另一種替代方法是使用一些綠色線程庫,例如libdill ,理論上它即使在不支持本機多線程的系統中也可以啟用多線程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM