关于c++:c-stdthread-joindetach用法

detach

拆散线程,将对象示意的线程与调用线程拆散,容许它们彼此独立执行。
两个线程在没有阻塞或同步的状况下持续运行。留神,当任何一个完结执行时,它的资源都会被开释。让被创立的线程为后盾线程,否则主线程退出时,如果子线程没有退出则异样。

#include <iostream>
#include <thread>
using namespace std;
void func1() {
    cout << "func1" << endl;
}
void func2() {
    cout << "func2" << endl;
}
int main() {
    thread t1(func1);
    thread t2(func2);
    return 0;
}

如果间接执行下面的程序,会报错:

void func1() {
    std::cout << "func1" << std::endl;
}
void func2() {
    std::cout << "func2" << std::endl;
}

拆散后,则失常:

std::thread t1(func1);
t1.detach();
std::thread t2(func2);
t2.detach();

join

在下面的状况中,个别应用join来解决:

#include <iostream>
#include <thread>
using namespace std;
void func1() {
    cout << "func1" << endl;
}
void func2() {
    cout << "func2" << endl;
}
int main() {
    thread t1(func1);
    t1.join();
    thread t2(func2);
    t2.join();
    return 0;
}

然而还是有可能还是会呈现问题,异常情况下可能会存在资源泄露的问题,利用c++的rall机制,能够在析构函数中join,自定义线程类:

#include <iostream>
#include <thread>
using namespace std;
class my_thread {
public:
    my_thread(std::thread& t) :thread_(t) {}

    ~my_thread() {
        if (thread_.joinable()) {
            std::cout << "thread id: " << std::this_thread::get_id() << std::endl;
            thread_.join();
        }
    }

    my_thread(const my_thread& t) = delete;
    my_thread& operator = (const my_thread&) = delete;

private:
    std::thread& thread_;
};
void func1() {
    cout << "func1" << endl;
}
void func2() {
    cout << "func2" << endl;
}
int main() {
    
    thread t1(func1);
    my_thread my(t1);
    thread t2(func2);
    my_thread my2(t2);
    return 0;
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理