Skip to content

Instantly share code, notes, and snippets.

@hzhou
Last active April 25, 2022 21:36
Show Gist options
  • Save hzhou/3dea9e40952fa41ce7b430517820b337 to your computer and use it in GitHub Desktop.
Save hzhou/3dea9e40952fa41ce7b430517820b337 to your computer and use it in GitHub Desktop.
Hello World in MyDef with MPI and pthread
$ cat test.def
include: c/mpi.def
include: c/thread.def

page: test_send, mpi_frame, MPI_THREAD_MULTIPLE
    module: c
    run: mpiexec -np 2

    &call run_threads, 4
        $print Hello $mpi_id/$mpi_size, thread $thread_id
$ mydef_run test.def
PAGE: test_send
  --> [out/test_send.c]
gcc -std=c99 -g -O2 -o out/test_send out/test_send.c -lpthread -lmpi && mpiexec -np 2 out/test_send
Hello 0/2, thread 3
Hello 1/2, thread 3
Hello 1/2, thread 2
Hello 0/2, thread 2
Hello 0/2, thread 1
Hello 1/2, thread 1
Hello 0/2, thread 0
Hello 1/2, thread 0
$ cat out/test_send.c
/* link: -lpthread -lmpi  */
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <assert.h>

void * thread_fn(void *p);

int mpi_size;
int mpi_id;
pthread_t p_threads[1000];

int main(int argc, char** argv)
{
    int tn_ret;


    int mpi_thread_level;
    MPI_Init_thread(NULL, NULL, MPI_THREAD_MULTIPLE, &mpi_thread_level);
    assert(mpi_thread_level == MPI_THREAD_MULTIPLE);
    MPI_Comm_size(MPI_COMM_WORLD, &mpi_size);
    MPI_Comm_rank(MPI_COMM_WORLD, &mpi_id);

    for (int  i = 0; i<4; i++) {
        tn_ret = pthread_create(&p_threads[i], NULL, thread_fn, (void *) (intptr_t)i);
        if (tn_ret) {
            fprintf(stderr, "Error - pthread_create - %d\n", i);
            exit(-1);
        }
    }
    for (int  i = 0; i<4; i++) {
        pthread_join(p_threads[i], NULL);
    }

    MPI_Finalize();
    return 0;
}

void * thread_fn(void *p)
{
    int thread_id = (intptr_t)p;

    printf("Hello %d/%d, thread %d\n", mpi_id, mpi_size, thread_id);
    return NULL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment