c语言

c语言两个for循环如何并列运行

小亿
489
2023-11-24 23:50:11
栏目: 编程语言

在C语言中,可以使用多线程或多进程来实现两个for循环的并列运行。

使用多线程的方式如下:

#include <stdio.h>
#include <pthread.h>

void* threadFunc1(void* arg) {
    // 第一个for循环的代码
    for (int i = 0; i < 10; i++) {
        printf("Thread1: %d\n", i);
    }
    return NULL;
}

void* threadFunc2(void* arg) {
    // 第二个for循环的代码
    for (int i = 0; i < 10; i++) {
        printf("Thread2: %d\n", i);
    }
    return NULL;
}

int main() {
    pthread_t thread1, thread2;
    pthread_create(&thread1, NULL, threadFunc1, NULL);
    pthread_create(&thread2, NULL, threadFunc2, NULL);
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    return 0;
}

使用多进程的方式如下:

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

int main() {
    pid_t pid;
    pid = fork();
    if (pid == 0) {
        // 子进程执行的代码,第一个for循环
        for (int i = 0; i < 10; i++) {
            printf("Child Process: %d\n", i);
        }
    } else if (pid > 0) {
        // 父进程执行的代码,第二个for循环
        for (int i = 0; i < 10; i++) {
            printf("Parent Process: %d\n", i);
        }
    }
    return 0;
}

无论是使用多线程还是多进程的方式,都可以实现两个for循环的并列运行。

0
看了该问题的人还看了