c++ thread for quadcore
Can you tell me how can I set a thread to run all of the core of my cpu? I make a thread with: CreateThread(0, 0, Thread, (LPVOID)1, 0, 0); but it only run at 25% speed of my cpu, because it only takes 1 core to do calculates. How can I set it to use all the 4 for full sp开发者_开发知识库eed?
A thread will run on a single core at any one time, though it may be switched between cores by the OS. To have your application take advantage of more than one core then you will need more than one thread.
You can use CreateThread
to start these threads, or a wrapper around it such as boost::thread
, or the new C++11 std::thread
. If you have four threads (including the first one) then your app can run on 4 cores at once.
However, adding threads to an application is not something to do lightly. Multithreading is a complex topic, and can be hard to get right. There are many more difficulties that you may encounter and sources of bugs in multithreaded applications than in single-threaded ones. Consequently, there are many articles and books (including mine) on the topic of multithreaded programming.
Take it slow, read extensively about multithreaded programming, and then look at whether this is the best approach for your application, and how to best make use of those cores.
To use all the power of your 4 cores, you'll have to get some work to those 4 cores simultaneously.
When you create a thread, you give some work for 1 core. The execution of one thread is done sequencially, instruction by instruction, and one instruction can only be executed by 1 core.
To be able to use the 4 cores, create 4 threads.
A single thread cannot run in parallel on 4 cores, how should that be possible? Instead create more threads (perhaps 4) to utilize all the cores. These threads will then run in parallel to each other on their respective cores (in the perfect case).
精彩评论