简体   繁体   中英

Calling same function on multiple thread increases performance

In my Application i have structure some thing like below

if(iterationCount==-3)
{

  CreatFullNetwork(obj1)
}

if(iterationCount==-2)
{
  CreatFullNetwork(obj2)//Method is same as previous
}

if(iterationCount==-1)
{
//Obj1,2,3 are same object but the sorting order variables inside object are different
  CreatFullNetwork(obj3)//Method is same as previous
}

To increase performance i am planning to create 3 threads and run it parallel.Is this a good approach will it work. Note: CreatFullNetwork() is very huge method it has sub methods in it and creates lots of collections and updates them

In a comment you state that the function call is not CPU bound. It does not reach close to 100% CPU utilization. In which case it seems very unlikely that your program's performance is liable to be improved by multi-threading.

On top of that it seems that your code uses a lot of shared variables that are not synchronized. Before you could even contemplate running the code in parallel you'd need to deal with that issue. Typically there are two ways to do that:

  1. Serialize access to shared variables to avoid data races.
  2. Arrange for each thread a private copy of the information and variables it needs.

Generally speaking, option 2 is better since serialization has performance overhead due to the use of locks. However, option 2 may be hard to achieve and can have its own performance issues in case you need to copy a lot of data.

Most of this is moot if your code is not CPU bound. That said, perhaps the bottleneck is at a different machine. Perhaps the bottleneck is in database access. If the database can handle parallel access efficiently then perhaps threading will help.

The bottom line is that you need to have a much clearer understanding of what your code is doing and what is limiting performance before you can contemplate options to speed it up. Threading is not a universal panacea. It won't help speed up all programs, and you always need to know how best to deploy it.

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