Indeed, boost threads are the most platform-independent solution today. C++ also supports threads directly, although today there are more compilers that support boost.threads than there are compilers that support C++ threads.
I'll use C++ here (but switching to boost is trivial in these examples, just replace std:: with boost:: and switch the header file)
Here's a quick example: start 3 threads and let them print some stuff for a bit.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#include <thread>
#include <iostream>
void f(int id)
{
for(int n=0; n<10000; ++n)
std::cout << "Output from thread " << id << '\n';
}
int main()
{
std::thread t1(f, 1); // launch thread executiong function f() with argument 1
std::thread t2(f, 2), t3(f, 3); // two more threads, also executing f()
t1.join(); t2.join(); t3.join(); // wait for all three threads to finish before ending main()
}
|
if you run it, you may see output such as
Output from thread Output from thread 2
Output from thread 2
Output from thread 12
|
That happens because each operator<< prints to the same global object std::cout: thread 1 printed "Output from thread", then before it was able to print "1", thread 2 managed to print "Output from thread 2" twice, and another "Output from thread". Then thread 1 finally got to squeeze out its "1", and thread 2 finished its "2".
To solve such issues, mutual exclusion may be needed:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include <thread>
#include <iostream>
static std::mutex m; // global mutex object, visible from f() in all threads
void f(int id)
{
for(int n=0; n<10000; ++n)
{
std::lock_guard<std::mutex> lk(m); // acquire lock or wait until it is released
std::cout << "Output from thread " << id << '\n';
} // release lock
}
int main()
{
std::thread t1(f, 1), t2(f, 2), t3(f, 3);
t1.join(); t2.join(); t3.join();
}
|
Now the output is exactly 30000 lines, with no mix-ups, something like
Output from thread 1
Output from thread 2
Output from thread 2
Output from thread 3
Output from thread 1
Output from thread 3
|
There are many more ways to synchronize and communicate between threads, there are books written on the topic.