C:使用进程求解算术表达式

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

我正在尝试用不同的过程来求解表达式((a + b c)/(a-b + d-c)+ a b c d”。但是我不知道fork()是如何工作的。我知道这就像一个新线程,但是当操作完成后,如何将结果连接到另一个线程并完成每个“子代”?

我的代码:

int arithOpera (int a, int b, int c, int d){
    int pid, pid1, pid2, pid3, pid4, pid5, pid6, pid7, pid8, pid9; 
    pid = fork();
    int term1, term2, term3; 
    if (pid == 0) { 
        sol = term1 / term2; 
    } 
  
    else { 
        pid1 = fork(); 
        if (pid1 == 0) { 
            term3 *= d; 
        } 
        else { 
            pid2 = fork(); 
            if (pid2 == 0) { 
                term3 *= c; 
            } 
            else {
                pid3 = fork(); 
                if (pid3 == 0) { 
                    term3 = a*b; 
                } 
                else {
                    pid4 = fork(); 
                    if (pid4 == 0) { 
                        term2 -= c; 
                    } 
                    else {
                        pid5 = fork(); 
                        if (pid5 == 0) { 
                            term2 += d; 
                        } 
                        else {
                            pid6 = fork(); 
                            if (pid6 == 0) { 
                                term2 = a-b; 
                            } 
                            else {
                                pid7 = fork(); 
                                if (pid7 == 0) { 
                                    term1 += a; 
                                } 
                                else {
                                    pid8 = fork(); 
                                    if (pid8 == 0) { 
                                        term1 = b * c; 
                                    } 
                                    else {
                                        sol += term3;
                                        } 
                                    } 
                                } 
                            } 
                        } 
                    } 
                } 
            } 
        } 
    } 
    return sol;
}

我应该在不同的线程中执行每个操作。

c operating-system fork fork-join
1个回答
0
投票

首先,fork()生成新进程,而不是同一进程的线程,如果您需要创建新线程而不是另一个进程,则可以使用pthread库(1),在其中可以使用pthread_create(2)要生成新线程,请使用pthread_exit(3)将一个线程的结果返回到另一个线程,并使用pthread_join函数(4)将其捕获到所需的线程中。

但是,如果要使用fork功能,则需要在所有不同的进程之间生成一些共享内存,在这种情况下,您还需要知道可能出现的并发问题。 (如果您对并发编程一无所知,这种方式会更加复杂)。

[如果您希望我为您提供更广泛的说明,请告诉我。我在此处附上有关pthread库功能的手册页。

  1. pthread概述https://www.man7.org/linux/man-pages/man7/pthreads.7.html
  2. pthread_create https://www.man7.org/linux/man-pages/man3/pthread_create.3.html
  3. pthread_exit https://www.man7.org/linux/man-pages/man3/pthread_exit.3.html
  4. pthread_join https://www.man7.org/linux/man-pages/man3/pthread_join.3.html
© www.soinside.com 2019 - 2024. All rights reserved.