C++11 Multithreading - Create Threads

Constructor

C ++ 11 provides the Thread :: std, std::thread thread_object(callable),a Callable can be

1. A function pointer

2. A function object

3. A lambda expression

To Pass arguments to thread’s associated callable object or function just pass additional arguments to the std::thread constructor.
By default all arguments are copied into the internal storage of new thread.

#include <iostream> 
#include <thread> 
using namespace std; 

// A dummy function 
void foo(int x) { 
    for (int i = 0; i < x; i++) { 
        cout << "Thread using function pointer as callable\n"; 
    } 
} 

// A callable object 
class thread_obj { 
public: 
    void operator()(int x) { 
        for (int i = 0; i < x; i++) 
            cout << "Thread using function object as callable\n"; 
    } 
}; 

int main ()
{ 
    cout << "Threads 1 and 2 and 3 operating independently" << endl; 

    // This thread is launched by using function pointer as callable 
    thread th1(foo, 3); 

    // This thread is launched by using function object as callable 
    thread th2(thread_obj(), 3); 

    // Define a Lambda Expression 
    auto f = [](int x) { 
        for (int i = 0; i < x; i++) 
            cout << "Thread using lambda expression as callable\n"; 
    }; 
    // This thread is launched by using lamda expression as callable 
    thread th3(f, 3); 

    // Wait for the threads to finish 
    // Wait for thread t1 to finish 
    th1.join(); 
    // Wait for thread t2 to finish 
    th2.join(); 
    // Wait for thread t3 to finish 
    th3.join(); 
    return 0; 
} 

 

thread::join()

Once a thread is started then another thread can wait for this new thread to finish. For this another need need to call join() function on the std::thread object.

Example:

Suppose Main Thread has to start 10 Worker Threads and after starting all these threads, main function will wait for them to finish. After joining all the threads main function will continue.

 

Reference

https://www.geeksforgeeks.org/multithreading-in-cpp/

https://thispointer.com//c-11-multithreading-part-1-three-different-ways-to-create-threads/

https://thispointer.com/c11-multithreading-part-2-joining-and-detaching-threads/

https://thispointer.com/c11-multithreading-part-3-carefully-pass-arguments-to-threads/

Guess you like

Origin www.cnblogs.com/hankunyan/p/11669212.html