C言語で並列に実行する2つのforループ
C言語において、2つの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;
}
マルチスレッドでも、マルチプロセスでも、2つのforループを並列に実行することは可能である。