Search code examples
cmultithreadingpthreadsopenmpsystems-programming

Openmp parallel for loop syntax in linux C with pthreads


I had done the below code with openmp, but the function

nvme_identify(fd, 0, 1, data);      

in turn invokes ioctl() which a blocking system call for nvme. So to have true parallelism I am looking to have the same code with pthreads.

I am new to pthreads, so can anybody get me the syntax in pthreads for the below openmp code?

#pragma omp parallel for num_threads(5)
for(i=0; i<rc; i++){
      err = nvme_identify(fd, 0, 1, data);
}

Solution

  • Pthreads unlike OpenMP kinda works manuel. As a pseudocode you may try something like this:

    In main()

    create a struct for parameters to use in nvme_identify(fd, 0, 1, data)
    Let's say my_struct[NUM_OF_THREADS]
    NUM_OF_THREADS is (as you gussed) number of threads you'll spawn.

    Fill the parametes correctly, i.e.:
    my_struct[0].fd = fd
    my_struct[0].data = data
    ...

    create pthreads with a for loop like:

    for (i=0; i < NUM_OF_THREADS; i++) pthreads_create(...., MyThreadedFunction, (void*)&my_struct[i]);

    In MyThreadedFunction(void *val) recover parameters like this:
    struct my_struct_tag *my_struct = (struct my_struct_tag *)val;
    int fd = my_struct->fd
    ...
    and call err = nvme_identify(fd, 0, 1, data)

    Adjust parameters correctly for maximum parallelism.
    In main you'll need to use pthread_join to wait for all threads completes.

    There may be error here and there in my logic. This is a quick answer. Hope that helps.