C++11並發——多線程std::thread (一)


https://www.cnblogs.com/haippy/p/3284540.html

與 C++11 多線程相關的頭文件

C++11 新標准中引入了四個頭文件來支持多線程編程,他們分別是<atomic> ,<thread>,<mutex>,<condition_variable>和<future>。

  • <atomic>:該頭文主要聲明了兩個類, std::atomic 和 std::atomic_flag,另外還聲明了一套 C 風格的原子類型和與 C 兼容的原子操作的函數。
  • <thread>:該頭文件主要聲明了 std::thread 類,另外 std::this_thread 命名空間也在該頭文件中。
  • <mutex>:該頭文件主要聲明了與互斥量(mutex)相關的類,包括 std::mutex 系列類,std::lock_guard, std::unique_lock, 以及其他的類型和函數。
  • <condition_variable>:該頭文件主要聲明了與條件變量相關的類,包括 std::condition_variable 和 std::condition_variable_any。
  • <future>:該頭文件主要聲明了 std::promise, std::package_task 兩個 Provider 類,以及 std::future 和 std::shared_future 兩個 Future 類,另外還有一些與之相關的類型和函數,std::async() 函數就聲明在此頭文件中。

簡單例子

#include <QCoreApplication>
#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <mutex>          // std::mutex, std::lock_guard
#include <stdexcept>      // std::logic_error

std::mutex mtx;

void thread_task()
{
    std::cout << "hello thread" << std::endl;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    std::thread t(thread_task);
    t.join();

    return a.exec();
}

 

std::thread 在 <thread> 頭文件中聲明,因此使用 std::thread 時需要包含 <thread> 頭文件。

std::thread 構造

default (1)
thread() noexcept;
initialization (2)
template <class Fn, class... Args>
explicit thread (Fn&& fn, Args&&... args);
copy [deleted] (3)
thread (const thread&) = delete;
move (4)
thread (thread&& x) noexcept;
  • (1). 默認構造函數,創建一個空的 thread 執行對象。
  • (2). 初始化構造函數,創建一個 thread對象,該 thread對象可被 joinable,新產生的線程會調用 fn 函數,該函數的參數由 args 給出。
  • (3). 拷貝構造函數(被禁用),意味着 thread 不可被拷貝構造。
  • (4). move 構造函數,move 構造函數,調用成功之后 x 不代表任何 thread 執行對象
  • 注意:可被 joinable 的 thread 對象必須在他們銷毀之前被主線程 join 或者將其設置為 detached.
#include <QCoreApplication>
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>

void f1(int n)
{
    for (int i = 0; i < 5; ++i) {
        std::cout << "Thread " << n << " executing\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}

void f2(int& n)
{
    for (int i = 0; i < 5; ++i) {
        std::cout << "Thread 2 executing\n";
        ++n;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    int n = 0;
    std::thread t1; // t1 is not a thread
    std::thread t2(f1, n + 1); // pass by value
    std::thread t3(f2, std::ref(n)); // pass by reference
    std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread

    t2.join();
    t4.join();
    std::cout << "Final value of n is " << n << '\n';


    return a.exec();
}
std::thread 各種構造函數例子

 

move 賦值操作

move (1)
thread& operator= (thread&& rhs) noexcept;
copy [deleted] (2)
thread& operator= (const thread&) = delete;
  • (1). move 賦值操作,如果當前對象不可 joinable,需要傳遞一個右值引用(rhs)給 move 賦值操作;如果當前對象可被 joinable,則 terminate() 報錯。
  • (2). 拷貝賦值操作被禁用,thread 對象不可被拷貝。

請看下面的例子:

#include <QCoreApplication>
#include <stdio.h>
#include <stdlib.h>

#include <chrono>    // std::chrono::seconds
#include <iostream>  // std::cout
#include <thread>    // std::thread, std::this_thread::sleep_for


void thread_task(int n) {
    std::this_thread::sleep_for(std::chrono::seconds(n));
    std::cout << "hello thread "
        << std::this_thread::get_id()
        << " paused " << n << " seconds" << std::endl;
}
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    std::thread threads[5];
     std::cout << "Spawning 5 threads...\n";
     for (int i = 0; i < 5; i++) {
         threads[i] = std::thread(thread_task, i + 1);
     }
     std::cout << "Done spawning threads! Now wait for them to join\n";
     for (auto& t: threads) {
         t.join();
     }
     std::cout << "All threads joined.\n";


    return a.exec();
}
Spawning 5 threads...
Done spawning threads! Now wait for them to join
hello thread 2 paused 1 seconds
hello thread 3 paused 2 seconds
hello thread 4 paused 3 seconds
hello thread 5 paused 4 seconds
hello thread 6 paused 5 seconds
All threads joined.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM