3

Possible Duplicate:
Simple example of threading in C++

Can someone please give me an example how to create a simple application in C++ that runs two functions simultaneously? I know that this question have connections with thread management and multi-threading, but I'm basically a php programmer and I'm not really familiar with advanced C++ programming.

11
  • Use thread class from boost and C++11! Commented Nov 18, 2012 at 18:22
  • Imp : Boost is a wrapper over pthreads. So you might want to have a look at pthreads. Commented Nov 18, 2012 at 18:25
  • Is my question that much not-useful that I deserve "-1" for it? Commented Nov 18, 2012 at 18:26
  • 2
    @faridv this is a very good book manning.com/williams and there are many samples on the website, it's also really up-to-date to the latest C++ standard Commented Nov 18, 2012 at 18:36
  • 1
    @user1824407: New answers can be posted to old questions. For instance, that 2008 question has an answer with a C++11 example. Commented Nov 18, 2012 at 18:41

2 Answers 2

11

Here's a simple example:

#include <iostream> #include <thread> void f1() { std::cout << "This is function 1.\n"; } void f2() { std::cout << "This is a different function, let's say 2.\n"; } int main() { std::thread t1(f1), t2(f2); // run both functions at once // Final synchronisation: // All running threads must be either joined or detached t1.join(); t2.join(); } 

If your functions need to produce return values, you should combine the above thread objects with std::packaged_task runnable objects, available from <future>, which give you access to the return value of the thread function.

Sign up to request clarification or add additional context in comments.

Comments

2

I'm going to let you do the research yourself but a simple way to achieve this is with std::async:

http://en.cppreference.com/w/cpp/thread/async

Note that it is concurrently, but not necessarily simultaneously.

I believe Boost has this too - it's either in Boost.Thread or Boost.ASIO

1 Comment

std::async doesn't really promise any particular order of execution. Also, it's more suitable for producing a value asynchronously rather than "running a function simultaneously"... Maybe I could get behind an std::packaged_task, but for the purpose of exposition, a flat std::thread seems to suffice.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.