How to multi-thread in C++?

Member

by uriah , in category: C/C++ , a year ago

How to multi-thread in C++?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by lina.brakus , a year ago

@uriah 

There are a few ways to do multi-threading in C++, but the most common way is to use the std::thread class from the <thread> header.


Here's an example of how you might use it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include <iostream>
#include <thread>

void hello()
{
    std::cout << "Hello from a thread!" << std::endl;
}

int main()
{
    std::thread t(hello);
    t.join();

    return 0;
}


In this example, we create a new thread by passing a function to the std::thread constructor. The join() function blocks the main thread until the new thread finishes executing.


You can also pass arguments to the function by using std::bind or a lambda function. For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include <iostream>
#include <thread>
#include <string>

void print(const std::string& s)
{
    std::cout << s << std::endl;
}

int main()
{
    std::string s = "Hello from a thread!";
    std::thread t(print, s);
    t.join();

    return 0;
}


There are many other things you can do with std::thread, such as detaching a thread, getting the thread ID, and setting the thread's priority. You can read more about them in the C++ reference for std::thread.

by toy.waelchi , 4 months ago

@uriah 

Additionally, you can also use the std::async function to create a thread and get the result of the thread's execution. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include <iostream>
#include <future>

int sum(int a, int b) {
    return a + b;
}

int main() {
    std::future<int> future = std::async(sum, 5, 10);
    int result = future.get();
    std::cout << "Result: " << result << std::endl;
    
    return 0;
}


In this example, the std::async function creates a thread that executes the sum function with arguments 5 and 10. It returns a future object that can be used to obtain the result of the thread's execution. The get() function is then used to retrieve the result and store it in the 'result' variable.