how do you create a muilt-threaded program?

Started by
3 comments, last by SiCrane 18 years, 9 months ago
i mean, this is a normal c++ program that i think is single threaded:

#include <iostream>
using namespace std;

int main(){
   cout "Hello World!";
   return 0;
}

(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.
Charles Reed, CEO of CJWR Software LLC
Advertisement
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.
HardDrop - hard link shell extension."Tread softly because you tread on my dreams" - Yeats
Theres a good tutorial here.
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):

#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)}
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
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