user2537688
user2537688

Reputation: 87

Dividing data for multithreaded processing

I am trying to learn about multithreading and how to use it to perform tasks on a set of data in parallel. For example if I have a array of numbers that I want to perform a rather long operation on, I have created the following code to process it:

mutex mm;
int nums[] = {10,20,30,40,50,60,70,80,90};
int index = 0;

void threadProc()
{
    while (index != sizeof(nums)/sizeof(nums[0])) //While != to end of array
    {
        mm.lock();
        int num = nums[index]; //Create local copy so we can unlock mutex for other threads
        index++;
        mm.unlock();
        cout << num + 2; //Replace with time-consuming function
    }
}

int main()
{
    //Create 2 threads
    thread t(threadProc);
    thread a(threadProc);
    t.join();
    a.join();
}

Since I am creating this code based off of what I seem logical, is this the proper way to do this? Of course I could add more threads based on the amount of hardware threads the CPU has, but I am going for the general idea here. If there are any good resources on this (preferably C++ oriented), I would be glad to hear about them. Thanks!

Upvotes: 1

Views: 350

Answers (2)

Jos&#233;  Fuentes
Jos&#233; Fuentes

Reputation: 182

In general, you have two options: Thread-based parallelism or Task-based parallelism. The first is the most traditional approach and pthreads and OpenMP are a good examples of it. In the second alternative, you have one more abstraction level, where you see your parallel program as a set of tasks that are mapped to threads. A good reference to learn the model of computation is the chapter 27 of Introduction to Algorithms of Cormen (http://mitpress.mit.edu/sites/default/files/titles/content/9780262033848_sch_0001.pdf) and some tools to program are CilkPlus (http://cilkplus.org/), Threading Building Blocks (http://threadingbuildingblocks.org/), OpenMP Tasks(http://openmp.org/wp/), and Microsoft’s Task Parallel Library (http://msdn.microsoft.com/en-us/library/dd460717.aspx).

Finally, you can read The Art of Multiprocessor Programming (http://www.amazon.com/The-Multiprocessor-Programming-Maurice-Herlihy/dp/0123705916)

Upvotes: 2

Mike Makuch
Mike Makuch

Reputation: 1838

I learned years ago with OReilly's Pthread Programming book and I see it referenced here too Multithreaded programming C++

Upvotes: 0

Related Questions