多进程与多线程

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

我一直在尝试使用多进程和多线程来测量同一任务的运行时间。我期望看到线程方法更快,因为线程上下文切换比进程切换更快。

任务是创建 3 个元素(进程/线程)并用每个元素打印 1 到 1,000,000。我在这里做错了什么吗?

处理方法代码:

#include <stdio.h>
#include <unistd.h>
#include <wait.h>
#include <semaphore.h>
#include <fcntl.h>

sem_t mutex;

int main() {
    int i;
    int N = 1;
    close(STDOUT_FILENO);
    open("multiproc.txt", O_WRONLY | O_CREAT, 0666);
    sem_init(&mutex, 1, 1);
    for(i=0; i<2; i++) {
        pid_t child_pid = fork();
        if(child_pid == 0) {
            N = i + 2;
            break;
        }
    }
    for(i=1; i<=1000000; i++) {
        sem_wait(&mutex);
        printf("Element: %d : %d\n", N, i);
        sem_post(&mutex);
    }
    if(N == 1) {
        while (wait(NULL) > 0);
        sem_destroy(&mutex);
        close(STDOUT_FILENO);
    }
    return 0;
}

线程方法代码:

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <fcntl.h>

sem_t mutex;

void* mythread(void* arg) {
    int n = *(int*)arg;
    int i;
    for(i = 1; i <= 1000000; i++) {
        sem_wait(&mutex);
        printf("Element: %d : %d\n", n, i);
        sem_post(&mutex);
    }
}

int main(void) {
    close(STDOUT_FILENO);
    open("multithread.txt", O_WRONLY | O_CREAT, 0666);
    sem_init(&mutex, 0, 1);
    pthread_t thr[3];
    for(int n = 0; n < 3; n++)
        pthread_create(&thr[n], NULL, mythread, &n);
    for(int n = 0; n < 3; n++)
        pthread_join(thr[n], NULL);
    sem_destroy(&mutex);
    close(STDOUT_FILENO);
}

我使用信号量并使用 gcc

-pthread
-lrt
标志进行编译。

测量的时间为:

abcd@abcd-Virtual-Machine:~/Desktop$ time ~/Desktop/multiproc

real    0m0.173s
user    0m0.281s
sys 0m0.047s
abcd@abcd-Virtual-Machine:~/Desktop$ time ~/Desktop/multithread

real    0m1.186s
user    0m0.664s
sys 0m1.489s
c ubuntu hyper-v ubuntu-22.04
1个回答
0
投票

“如果 pshared 非零,则信号量在进程之间共享,并且应该位于共享内存区域”

您的代码不符合此要求。因此,每个进程最终都会有不同的信号量,因此它们永远不会等待。

© www.soinside.com 2019 - 2024. All rights reserved.