原创

MPI、OpenMP与pthread的测试例程


这学期在上并行计算的课,配置环境的时候需要测试环境是否配置成功,下面是三个小Demo,用来测试环境是否配置成功。
mpi不需要安装,gcc自带了OpenMP,如果没有gcc可以使用apt安装,MPI也可以使用apt install mpich轻松安装,而pthread也是标准库中自带的,不需要安装。

pthread例程

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
 
int thread_count;
 
void* Hello(void* rank);
 
int main(int argc, char* argv[])
{
    long thread = 0;
 
    pthread_t* thread_handles;
 
    thread_count = strtol(argv[1], NULL, 10);
 
    thread_handles = malloc(thread_count * sizeof(pthread_t));
 
    for(thread = 0; thread < thread_count; thread++)
    {
        pthread_create(&thread_handles[thread], NULL, Hello, (void*) thread);
    }
 
    for(thread = 0; thread < thread_count; thread++)
    {
        pthread_join(thread_handles[thread], NULL);
    }
 
    free(thread_handles);
    return 0;
}
 
void* Hello(void* rank)
{
    long my_rank = (long) rank;
    printf("Hello from thread %ld of %d\n", my_rank, thread_count);
 
    return NULL;
}

编译命令:gcc -g -Wall -o pth_hello pth_hello.c -lpthread
运行命令:./pth \<number of threads>

OpenMP例程

#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
 
void Hello(void);
 
int main(int argc, char* argv[])
{
    int thread_count = strtol(argv[1], NULL, 10);
 
#   pragma omp parallel num_threads(thread_count)
    Hello();
 
    return 0;
}
 
void Hello(void)
{
    int my_rank = omp_get_thread_num();
    int thread_count = omp_get_num_threads();
 
    printf("Hello from thread %d of %d\n", my_rank, thread_count);
}

编译命令:gcc -fopenmp -o omp_hello omp_hello.c
运行命令:./pth \<number of threads>

MPI例程

#include <stdio.h>
#include <string.h>
#include <mpi.h>
 
const int MAX_STRING = 100;
int main()
{
    char greeting[MAX_STRING];
    int comm_sz;
    int my_rank;
    int i = 1;
 
    MPI_Init(NULL, NULL);
    MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
 
    if (my_rank != 0)
    {
        sprintf(greeting, "Greetings from process %d of %d!",my_rank, comm_sz);
        MPI_Send(greeting, strlen(greeting)+1, MPI_CHAR, 0, 0, MPI_COMM_WORLD);
    }else{
        printf("Gteetings from process %d of %d!\n",my_rank, comm_sz);
        for(i = 1; i < comm_sz; i++)
        {
            MPI_Recv(greeting, MAX_STRING, MPI_CHAR, i, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
            printf("%s\n", greeting);
        }
    }
 
    MPI_Finalize();
    return 0;
}

编译命令:mpicc -o Hello_mpi Hello_mpi.c
运行命令:mpirun -n 16 ./Hello_mpi

环境配置
  • 作者:Daozhi(联系作者)
  • 发表时间:2021-04-26 03:39
  • 版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)
  • 公众号转载:请在文末添加作者公众号二维码
  • 评论