Click here to Skip to main content
15,890,506 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a code which has a loop which takes around 2 hrs to complete one iteration. I have to execute 12 iterations and therefore the code takes around 24 hrs to complete. I have a 16 core processor to my access. I wish to parallelize the loop such that I have 12 threads, each executing one iteration on one core. This will bring down the execution time to 2 hrs. I have achieved the parallel code but however, there is a conflict for the data to be read from from a global array. How do I resolve that?
My code is in c++
Posted
Comments
Niklas L 8-Jun-11 9:16am    
There can be no conflict reading data. Are you writing to the array as well? It's impossible to answer your question without more information on how you do it.

As Niklas Lindquist mentions: If the data is availalbe in memory before the threads start - possibly using a memory mapping - and the data is not altered by the threads. there is no need to protect the memory using a locking mechanism, just access at will. If each thread writes it's results to a separate memory area you will not need a locking mechanism in place for that either.

Locking is only needed when you want to coordinate updates between threads - even if only one is writing and several others are reading.

Best regards
Espen Harlinn
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 17-Jun-11 3:20am    
Good point, a 5.
--SA
Espen Harlinn 17-Jun-11 12:53pm    
Thank you, SAKryukov!
don't use global data; it's an anathema to multi-threaded code ...

By all means use a data pointer which is created by the master thread and used by the children ....

What conflict are you experiencing? reading the data should be fine, however, if you're writing data into anything that's shared you must use some form of synchronisation
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 17-Jun-11 3:22am    
It's not about "global", it's about "shared". You're basically right about anathema, but in real time not sharing data at all is simply not realistic. My 4.
--SA
Use a mutex variable if you need to control access to a data array from multiple threads.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 17-Jun-11 3:24am    
I would say "critical section" first (we do not know platform though) if you're talking about threads in the same process. Mutex (named) can also do IPC; same thread synchronization, but working in different processes as well. My 4.
--SA
Thanks. :)
Apparently the conflict was in writing the data to the files... All of them were accessing the same file together.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900