【C++】join ()和detach ()函数详解和示例

简单的来说,join ()方法建立的线程具有阻碍作用,该线程不结束,另一些函数就无法运行。detach ()方法建立的线程,可以和另一些函数同时进行。下面以示例进行详细说明,以帮助大家理解和使用。

join ()

join 方法用于等待线程结束。当一个线程对象调用 join 方法时,当前线程将阻塞,直到该线程对象所代表的线程结束。如果该线程对象所代表的线程已经处于结束状态,则 join 方法立即返回。注意,如果一个线程对象被析构(也就是离开其作用域),而该线程对象所代表的线程仍在运行,程序将终止。

以下是一个 join 的示例:

#include <iostream>
#include <thread>

void threadFunction() {
    std::cout << "Hello from the thread!\n";
}

int main() {
    int i = 3;
    while (i) 
    {
        std::thread t(threadFunction);  // 创建一个新线程,t 是该线程的对象
        t.join();  // 等待新线程结束
        std::cout << "Hello from the main thread!\n";
        i--;
    }
   
    return 0;
}

输出:

Hello from the thread!
Hello from the main thread!
Hello from the thread!
Hello from the main thread!
Hello from the thread!
Hello from the main thread!

在这个例子中,先建立一个while()循环,执行三次主程序中内容。程序首先创建一个新线程并开始运行 threadFunction。然后,主线程调用 t.join(),这将阻塞主线程,直到新线程结束。当新线程结束时,主线程将继续执行,输出 “Hello from the main thread!”。
在这里插入图片描述
从输出结果中可以看出,主程序输出和线程输出有着先后顺序,与原理一致。

detach ()

在C++中,std::thread::detach()函数用于将线程“分离”出当前对象。当一个线程对象调用detach()方法时,该线程对象将不再与该线程有任何关联。一旦线程分离出来,它将独立运行,直到完成。注意,一旦线程完成,系统会自动回收其资源。

下面是一个使用std::thread::detach()函数的示例:

#include <iostream>
#include <thread>

void threadFunction() {
    while (1)
    {
        std::cout << "Hello from the thread!\n";
    }
  
}

int main() {
    int i = 3;
    while (i) {
        std::thread t(threadFunction);  // 创建一个新线程,t 是该线程的对象
        t.detach();  // 将新线程分离出去,它将继续运行直到完成
        std::cout << "Hello from the main thread!\n";  // 这会立即输出,不会等待新线程结束
        i--;
    }
 
    return 0;
}

输出:

Hello from the main thread!
Hello from the main thread!
Hello from the main thread!
Hello from the thread!
Hello from the thread!
Hello from the thread!
Hello from the thread!

在这里插入图片描述

在这个例子中,也是先用一个while循环。从输出的结果可以看出,与join()的有序性不同,建立的线程和主线程是在同时进行的。

需要注意的是,一旦线程被分离出去,它就不再受原线程的控制和影响。因此,无法通过原线程来获取该线程的执行结果或等待其结束。如果需要等待线程执行完毕后再继续执行其他操作,可以使用 join() 方法来阻塞等待线程结束。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木彳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值