How to thread easily in C++

Asked 2 years ago, Updated 2 years ago, 142 views

Instead of using a thread library like C, Looking for C++ style (object-oriented) thread objects.

Please teach me the easiest way to thread in C++! Is there anyone who can post an example of a program where you spin two threads?

multithreading c++

2022-09-22 22:29

1 Answers

I'll explain it with comments in the code.

#include <string>
#include <iostream>
#include <thread> //header file for threads

using namespace std;

// Set a function that the thread should execute
void task1(string msg)
{
    cout << "task1 says: " << msg;
}

int main()
{
    // Create and run a new thread. The current thread is not blocked.
    thread t1(task1, "Hello");

    // Make the main wait for the newly created thread to finish the work.
    t1.join();
}

When compiling into GCC, make sure to write -std=c++0x-pthread For more information, see std::stread


2022-09-22 22:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.