开发者

Transforming code to multithread version

开发者 https://www.devze.com 2023-03-02 13:32 出处:网络
I have the followingproblem: for example, I have 10 lists, each one has a link to some other lists, I would like to create a code to search 开发者_StackOverflowelements in theses lists, I\'ve alread

I have the following problem:

  • for example, I have 10 lists, each one has a link to some other lists, I would like to create a code to search 开发者_StackOverflowelements in theses lists, I've already done this algorithm but sequentially, it start the search in the first list, then if the search is failed, it send messages for searching in lists that have a link with it (to the first one), at the end of the algorithm, he show the results as the number of lists visited and if he find the element or no.
  • now, I want to transform it to be a parallel algorithm, at least a concurrent one using multi-threads:
    • to use threads for searching;
    • to start a search in the 10 lists at the same time;


As long as you don't change anything, you can consider your search read only. In that case, you probably don't need synchronization. If you want to have a fast search, don't use threads directly but use runnables and look for the appropriate classes. If you do work directly with threads, make sure that you don't exceed the number of processors.

Before going further, read into multi-threading. I would mention "Java Concurrency in Practice" as a (rather safe) recommendation. It's too easy to get wrong.


I am not sure from your problem statement if there is a sequential dependency between the searches in different lists, namely whether search results from the first list should take priority over those from the second list or not.

Assume there's no such dependency, so that any search result from any list is fine, then this is expressed in a very concise way as a speculative search in Ateji PX:

Object parallelSearch(Collection<List> lists)
{
  // start of parallel block
  [
    // create one parallel branch for each of the lists
    || (List list: lists) {

       // start searching lists in parallel
       Object result = search(list);

       // the first branch that finds a result returns it, 
       // thereby stopping all remaining parallel branches
       if(result != null) return result;
    }
  ]
}

The term "speculative" means that you run a number of searches in parallel although you know that you will use the result of only one of them. Then as soon as you have found a result in one of the searches, you want to stop all the remaining searches.

If you run this code on a 4-core machine, the Ateji PX runtime will schedule 4 parallel branches at a time in order to make the best use of the available parallel hardware.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号