C++多线程基础-thread


学习C++多线程的笔记,用于提高算法的性能;

注意:
No two std::thread objects may represent the same thread of execution; std::thread is not CopyConstructible or CopyAssignable, although it is MoveConstructible and MoveAssignable.


使用多线程的原因:

1、分离任务,例如将界面和后台文件读写相分离;

2、提高性能,任务并行(task parallelism)和数据并行(data parallelism);

3、线程存在开销,上下文切换开销、堆栈空间等,管理困难,所以只在必要时使用;

4、使用线程池,避免线程数量爆炸问题;

基本使用:

1、线程构造;

2、等待线程执行结束线程:join

3、线程分离:detach


可以用可执行对象、函数、类函数、转移构造来构造线程对象。

#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
 
void f1(int n)
{
    
    
    for (int i = 0; i < 5; ++i) {
    
    
        std::cout << "Thread 1 executing\n";
        ++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));
    }
}
 
class foo
{
    
    
public:
    void bar()
    {
    
    
        for (int i = 0; i < 5; ++i) {
    
    
            std::cout << "Thread 3 executing\n";
            ++n;
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
        }
    }
    int n = 0;
};
 
class baz
{
    
    
public:
    void operator()()
    {
    
    
        for (int i = 0; i < 5; ++i) {
    
    
            std::cout << "Thread 4 executing\n";
            ++n;
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
        }
    }
    int n = 0;
};
 
int main()
{
    
    
    int n = 0;
    foo f;
    baz b;
    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
    std::thread t5(&foo::bar, &f); // t5 runs foo::bar() on object f
    std::thread t6(b); // t6 runs baz::operator() on a copy of object b
    t2.join();
    t4.join();
    t5.join();
    t6.join();
    std::cout << "Final value of n is " << n << '\n';
    std::cout << "Final value of f.n (foo::n) is " << f.n << '\n';
    std::cout << "Final value of b.n (baz::n) is " << b.n << '\n';
}

join阻塞当前线程,直到*this标识的线程完成执行。由 *this标识的线程的完成与join()相应的成功返回同步。

*this本身不执行同步。从多个线程并发调用同一个线程对象上的join()会导致未定义行为的数据竞争。

#include <iostream>
#include <thread>
#include <chrono>
 
void foo()
{
    
    
    // simulate expensive operation
    std::this_thread::sleep_for(std::chrono::seconds(1));
}
 
void bar()
{
    
    
    // simulate expensive operation
    std::this_thread::sleep_for(std::chrono::seconds(1));
}
 
int main()
{
    
    
    std::cout << "starting first helper...\n";
    std::thread helper1(foo);
 
    std::cout << "starting second helper...\n";
    std::thread helper2(bar);
 
    std::cout << "waiting for helpers to finish..." << std::endl;
    helper1.join();
    helper2.join();
 
    std::cout << "done!\n";
}

detach将执行线程与线程对象分离,允许执行单独继续。一旦线程退出,任何已分配的资源都将被释放。

调用detach 后,它不再拥有任何线程。

#include <iostream>
#include <chrono>
#include <thread>
 
void independentThread() 
{
    
    
    std::cout << "Starting concurrent thread.\n";
    std::this_thread::sleep_for(std::chrono::seconds(2));
    std::cout << "Exiting concurrent thread.\n";
}
 
void threadCaller() 
{
    
    
    std::cout << "Starting thread caller.\n";
    std::thread t(independentThread);
    t.detach();
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << "Exiting thread caller.\n";
}
 
int main() 
{
    
    
    threadCaller();
    std::this_thread::sleep_for(std::chrono::seconds(5));
}

hardware_concurrency返回实现支持的并发线程数。该值应该被认为只是一个提示。

#include <iostream>
#include <thread>
 
int main() {
    
    
    unsigned int n = std::thread::hardware_concurrency();
    std::cout << n << " concurrent threads are supported.\n";
}

get_id返回std::thread::id值,标识与*this相关的线程。

#include <iostream>
#include <thread>
#include <chrono>
 
void foo()
{
    
    
    std::this_thread::sleep_for(std::chrono::seconds(1));
}
 
int main()
{
    
    
    std::thread t1(foo);
    std::thread::id t1_id = t1.get_id();
 
    std::thread t2(foo);
    std::thread::id t2_id = t2.get_id();
 
    std::cout << "t1's id: " << t1_id << '\n';
    std::cout << "t2's id: " << t2_id << '\n';
 
    t1.join();
    t2.join();
}

joinable检查std::thread对象是否标识正在执行的活动线程。具体来说,如果get_id() != std::thread::id()则返回true。因此,默认构造的线程是不可join的。已经完成代码执行但尚未join的线程仍然被认为是执行的活动线程,因此是join的。

#include <iostream>
#include <thread>
#include <chrono>
using namespace std::chrono_literals;
 
void foo()
{
    
    
    std::this_thread::sleep_for(500ms);
}
 
int main()
{
    
    
    std::cout << std::boolalpha;
 
    std::thread t;
    std::cout << "before starting, joinable: " << t.joinable() << '\n';
 
    t = std::thread{
    
    foo};
    std::cout << "after starting, joinable: " << t.joinable() << '\n';
 
    t.join();
    std::cout << "after joining, joinable: " << t.joinable() << '\n';
 
    t = std::thread{
    
    foo};
    t.detach();
    std::cout << "after detaching, joinable: " << t.joinable() << '\n';
    std::this_thread::sleep_for(1500ms);
}

参考:

std::thread::thread - cppreference.com

猜你喜欢

转载自blog.csdn.net/KPer_Yang/article/details/130035334