Let me preface this by saying that multithreading in C++ is not a beginner topic. It is ripe with gotchas, pitfalls, and demands extreme care.
There are many different threading libs.
If you are using C++11, it has it's own (standard) threading lib (in the <thread> header) which is probably easier to use than most other libs. For that, you just create a std::thread object:
1 2 3 4 5 6 7 8 9 10
|
#include <thread>
void func()
{
}
int main()
{
std::thread thd( func);
}
|
This will create a new thread, represented by our 'thd' object. A thread is another code path that runs alongside your main code path. So with this code... once the 'thd' object is created, code inside both 'main' and 'func' will be running simultaneously.
However, even though they are two separate code paths, they share memory and resources. So all variables/objects/etc are shared between threads. Changes made to a var in one thread will be visible in another thread.
But this is where it gets complicated. Due to lots of factors, updating variables doesn't necessarily update the variable immediately. And if two different threads are trying to access the same variable at the same time,
very bad things happen.
Because of this, you need to be careful about which memory is being accessed by which threads and when. And if multiple threads need to share access to the same object, those accesses need to be guarded somehow (usually with a mutex).