Sign in to follow this  

how do you create a muilt-threaded program?

This topic is 4550 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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)
}


Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 4550 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this