简体   繁体   中英

Process singly linked list with OpenMP

The code I want to parallelize has the following simple form:

for(const ListItem* item = myList; item; item = item->getNext())
  doSthWith(item);

I compile on MSVC 2013 with omp 2.0 support. Is it possible to still parallelize this in a clean and efficient way? First problem I stumbled upon is that I need an integral loop counter. I could obviously just use an int and assign the pointer inside the loop but this already starts feeling like a kind of dirty workaround. Is iterating types like this even supported my the omp standard or might this end up in UB anyway?

Perhaps not really an answer, but I can't format code in a comment...

Assuming that the list is not being modified, you could write something somewhat unpleasant like this (typed in here, not compiled, not tested).

#pragma omp parallel
{
    int nThreads = omp_get_num_threads();
    int me       = omp_get_thread_num();
    int itemNo   = 0;

    for(const ListItem* item = myList; 
        item; 
        (item = item->getNext()), itemNo++)
    {
        if (itemNo%nThreads == me)
        {
            doSthWith(item);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM