#include <iostream>
using namespace std;
int main(){
cout "Hello World!";
return 0;
}
how do you create a muilt-threaded program?
i mean, this is a normal c++ program that i think is single threaded:
(before we go on, i'd like to point out i'm way pass this level of c++.)
but how do you than create a muilt-threaded program? thanks.
Quote:Original post by CJWR
but how do you than create a muilt-threaded program? thanks.
In a platform dependant manner, or I bet boost::probablysomethignwiththreadinit already have it nicely absracted on windows you want to CreateThread don't forget to read up on synchronization primitives like critical sections mutexes (mutices?) semaphores and common ideoms like bag of tasks, passing the baton and double checked locking if you plan on venturing into the mult-threaded realm.
You use a platform-specific library (e.g. Win32, pthreads...) that provides functions to create threads.
For example, using Boost (for cross-platform C++ threading):
For example, using Boost (for cross-platform C++ threading):
#include <boost/thread/thread.hpp>#include <boost/thread/mutex.hpp>boost::mutex mx;int x = 0;void foo(){ while(true) { boost::scoped_lock lock(mx); std::cout << "FOO: " << x << std::endl; --x; }}void bar(){ while(true) { boost::scoped_lock lock(mx); std::cout << "BAR: " << x << std::endl; ++x; }}int main(){ boost::thread foo_thread(foo); boost::thread bar_thread(bar); foo_thread.join(); // Waits until foo_thread terminates (never) bar_thread.join(); // Waits until bar_thread terminates (never)}
It's generally a bit more complicated than just writing the code (which is bad enough and then some, as Fruny showed). You also have to make sure that the compiler/linker settings for you compiler/linker are also set to multi-thread happily. For example, in MSVC, you'd want to use a multi-threaded version of the standard library, so that memory allocation across threads won't corrupt the heap, and so on.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement