YouTip LogoYouTip

Cpp Libs Thread

C++ Multithreading Library | \\n\\n

C++ Multithreading Library |

\\n \\n
\\n

C++11 introduced multithreading support, through<thread> Library,developers can easily implement parallel processing in programs.

\\n

This article will introduce <thread>Library'sbasic concepts, definitions, syntax, and how to Usage it to createand manage threads.

\\n

A thread is the program execution'ssmallest unit, which the operating system can schedule for computation'ssmallest unit.

\\n

In a multithreaded program, multiple threads can execute in parallel, improving program'sexecution efficiency.

\\n

C++<thread> LibraryOverview

\\n

<thread>The library is part of the C++ standard library, providing basic functionality for creating and managing threads. It includes the following key components:

\\n
    \\n
  • std::thread:represents a thread, can create, start, wait and Destroy Thread.
  • \\n
  • std::this_thread:provides some static member functions for operating on the current thread.
  • \\n
  • std::thread::id: The unique identifier of the thread.
  • \\n
\\n

Creating Threads

\\n

To create a thread, you need to instantiatestd::threadclass, and pass a callable object (function, lambda expression, or an object's member function) as a parameter.

Example

#include <iostream>\\n#include <thread>\\n\\nvoid print_id(int id){\\n    std::cout << "ID: " << id << ", Thread ID: " << std::this_thread::get_id() << std::endl;\\n}\\n\\nint main(){\\n    std::thread t1(print_id, 1);\\n    std::thread t2(print_id, 2);\\n}\\n
\\n

Starting a Thread

\\n

create std::thread object, the thread will start executing immediately, and you can call join() method to Wait for Thread Completion.

\\n
t1.join(); t2.join();\\n
\\n

Wait for Thread Completion

\\n

join()method blocks the current thread until called'sthread completes execution.

\\n

Destroy Thread

\\n

When the thread finishes execution, you can Usagedetach() method to detach the thread, or let std::thread The object is automatically destroyed when it goes out of scope.

\\n
t1.detach(); // the thread will continue to run, but can no longer be join or detach\\n
\\n

Example:Usage <thread> createParallel Computing

\\n

Below is a Usage <thread> LibraryImplementation'sParallel ComputingExample,calculate two numbers'sand。

\\n

Example

\\n
#include <iostream>\\n#include <thread>\\n\\nint sum =0;\\n\\nvoid add(int a, int b){\\n    sum += a + b;\\n}\\n\\nint main(){\\n    int a =5;\\n    int b =10;\\n    std::thread t1(add, a, b);\\n    std::thread t2(add, a, b);\\n    t1.join();\\n    t2.join();\\n    std::cout << "Sum: " << sum << std::endl;// Output: Sum: 30\\n}\\n
\\n

The output result is:

\\n
Sum: 30\\n

In the following example, we will create two threads, each executing a simple function that prints a message and sleeps for a period of time:

\\n

Example

#include <iostream>\\n#include <thread>\\n#include <chrono>\\n\\nvoid print_message(const std::string& message, int delay){\\n    std::this_thread::sleep_for(std::chrono::milliseconds(delay));\\n    std::cout<< message << std::endl;\\n}\\n\\nint main(){\\n    std::thread t1(print_message, "Hello from thread 1", 1000);\\n    std::thread t2(print_message, "Hello from thread 2", 500);\\n    if(t1.joinable()){\\n        t1.join();\\n    }\\n    if(t2.joinable()){\\n        t2.join();\\n    }\\n    std::cout<<"Main thread finished."<< std::endl;\\n    return 0;\\n}\\n
\\n

The output result is:

\\n
Hello from thread 2Hello from thread 1Main thread finished.\\n

Notes

\\n
    \\n
  • Thread Safety: In a multi-threaded environment, shared resources need synchronized access to avoid data races.
  • \\n
  • Thread Lifecycle: Ensure that thread objects are properly handled after thread execution completes to avoid resource leaks.
  • \\n
\\n

Classes and Functions

\\n

<thread>The library contains a series of classes and functions for creating, managing, and synchronizing threads.

\\n

Main Components

\\n
    \\n
  • std::thread
  • \\n
  • std::mutex
  • \\n
  • std::lock_guard
  • \\n
  • std::unique_lock
  • \\n
  • std::condition_variable
  • \\n
  • std::future and std::promise
  • \\n
  • std::async
  • \\n
\\n

std::thread

\\n

std::thread class is used to createand manage threads.

\\n

Example

\\n
#include <iostream>\\n#include <thread>\\n\\nvoid print_hello(){\\n    std::cout<<"Hello from thread!"<< std::endl;\\n}\\n\\nint main(){\\n    std::thread t(print_hello);\\n    t.join();\\n    return 0;\\n}\\n

Important Methods

\\n
    \\n
  • join():Wait for the thread to finish.
  • \\n
  • detach():run the thread in the background, no longer Wait for the thread to finish.
  • \\n
  • joinable(): Check if the thread can be joined or detached.
  • \\n
\\n

std::mutex

\\n

std::mutex class is used to synchronize shared resources'saccess.

\\n

Example

\\n
#include <iostream>\\n#include <thread>\\n#include <mutex>\\n\\nstd::mutex mtx;\\nint shared_resource =0;\\n\\nvoid increment(){\\n    std::lock_guard<std::mutex> lock(mtx);\\n    ++shared_resource;\\n    std::cout<<"Incremented shared_resource to "<< shared_resource << std::endl;\\n}\\n\\nint main(){\\n    std::thread t1(increment);\\n    std::thread t2(increment);\\n    t1.join();\\n    t2.join();\\n    std::cout<<"Final value of shared_resource: "<< shared_resource << std::endl;\\n    return 0;\\n}\\n
\\n

std::lock_guard

\\n

std::lock_guard is an RAII-style lock manager for automatically managing the lock lifecycle.

\\n

Example

#include <iostream>\\n#include <thread>\\n#include <mutex>\\n\\nstd::mutex mtx;\\n\\nvoid print_thread_id(int id){\\n    std::lock_guard<std::mutex> lock(mtx);\\n    std::cout<<"Thread ID: "<< id << std::endl;\\n}\\n\\nint main(){\\n    std::thread t1(print_thread_id, 1);\\n    std::thread t2(print_thread_id, 2);\\n    t1.join();\\n    t2.join();\\n    return 0;\\n}\\n
\\n

std::unique_lock

\\n

std::unique_lock provides more ... than std::lock_guard more flexible'slock management.

\\n

Example

\\n
#include <iostream>\\n#include <thread>\\n#include <mutex>\\n\\nstd::mutex mtx;\\n\\nvoid print_thread_id(int id){\\n    std::unique_lock<std::mutex> lock(mtx);\\n    std::cout<<"Thread ID: "<< id << std::endl;\\n    lock.unlock();\\n}\\n\\nint main(){\\n    std::thread t1(print_thread_id, 1);\\n    std::thread t2(print_thread_id, 2);\\n    t1.join();\\n    t2.join();\\n    return 0;\\n}\\n
\\n

std::condition_variable

\\n

std::condition_variable used for inter-thread'swait and notify.

\\n

Example

\\n
#include <iostream>\\n#include <thread>\\n#include <mutex>\\n#include <condition_variable>\\n\\nstd::mutex mtx;\\nstd::condition_variable cv;\\nbool ready =false;\\n\\nvoid print_id(int id){\\n    std::unique_lock<std::mutex> lock(mtx);\\n    cv.wait(lock, []{return ready;});\\n    std::cout<<"Thread ID: "<< id << std::endl;\\n}\\n\\nvoid set_ready(){\\n    std::unique_lock<std::mutex> lock(mtx);\\n    ready =true;\\n    cv.notify_all();\\n}\\n\\nint main(){\\n    std::thread t1(print_id, 1);\\n    std::thread t2(print_id, 2);\\n    std::this_thread::sleep_for(std::chrono::seconds(1));\\n    set_ready();\\n    t1.join();\\n    t2.join();\\n    return 0;\\n}\\n
\\n

std::future and std::promise

\\n

std::future and std::promise used for inter-thread'sresult passing.

\\n

Example

\\n
#include <iostream>\\n#include <thread>\\n#include <future>\\n\\nvoid calculate_square(std::promise<int>&& p, int x){\\n    p.set_value(x * x);\\n}\\n\\nint main(){\\n    std::promise<int> p;\\n    std::future<int> f = p.get_future();\\n    std::thread t(calculate_square, std::move(p), 5);\\n    std::cout<<"Square: "<< f.get</code></pre>\\n        

</code></pre>

\\n

std::async

\\n

std::async Used to start asynchronous tasks and return a std::future。

\\n

Example

\\n
#include <iostream>\\n#include <future>\\n\\nint calculate_square(int x){\\n    return x * x;\\n}\\n\\nint main(){\\n    std::future<int> result = std::async(calculate_square, 5);\\n    std::cout<<"Square: "<< result.get</code></pre>\\n        

</code></pre>

\\n

C++ 's <thread> Libraryprovides developers with powerful'smultithreading support. Through this article'sintroduction, we should be able to understand thread'sbasic concepts, and learn how to Usage <thread>

\\n

library to create and manage threads. In actual development, reasonable use of multithreading can significantly improve program performance and responsiveness.

\\n
← Cpp Libs Condition_VariableCpp Libs Ctime β†’

YouTip © 2024-2026 | Home | Learn Technology, Build Dreams!

All content is for educational and learning purposes only.