Do threads by default run on more than one core?

后端 未结 4 832
醉话见心
醉话见心 2021-02-05 17:55

In multi-core processors, and windows application runs many threads. do the threads by default run on more than one core ? I mean every thread might run on individual c

4条回答
  •  北荒
    北荒 (楼主)
    2021-02-05 18:33

    When you start multiple threads, they may, or may not, run on different cores.

    You can, if you absolutely must, force a thread to run a specific core by using the SetProcessorAffinity method of the Thread class. You really shouldn't do this unless you know why you need to do it.

    It is up to the operating system to schedule threads.

    To best take advantage of multiple cores, there are plenty of tutorials and knowledge articles out on the web, but here are some tips:

    • Divide up your work into smaller pieces, this avoids having really long-running threads that hog a single CPU
    • Try to avoid data contention, try to make sure each thread/task gets all the data it needs up front, and returns all the data it produces out the other end, instead of it having to go and talk to a data structure. This avoids locking problems or race conditions.
    • Use the runtime to help you, don't try to invent the wheel again. If you're in .NET 4.0, you should look at the TPL, Task Parallel Library, which will help you tremendously.
    • Lastly, multi-threading is hard, don't jump into this thinking you can wing it and learn as you go. Read up on the subject, study example code, learn about the pitfalls and how to avoid them.

提交回复
热议问题