1、简单的例子

#include "stdafx.h"
#include <iostream>
#include <thread>



void function_1() 
{
    for (size_t i = 0; i < 100; i++)
    {
        std::cout << "from function 1" << std::endl;
    }    
}

int main()
{
    std::thread t(function_1);

    for (size_t i = 0; i < 100; i++)
    {
        std::cout << "from function main"<<std::endl;
    }

    t.join();

    std::getchar();

    return 0;
}

在一个线程中,开了另一个线程去干另一件事,使用join函数后,原始线程会等待新线程执行结束之后,再去销毁线程对象。
这样有什么好处?---->因为它要等到新线程执行完,再销毁,线程对象,这样如果新线程使用了共享变量,等到新线程执行完再销毁这个线程对象,不会产生异常。如果不使用join,使用detch,那么新线程就会与原线程分离,如果原线程先执行完毕,销毁线程对象及局部变量,并且新线程有共享变量或引用之类,这样新线程可能使用的变量,就变成未定义,产生异常或不可预测的错误。
所以,当你确定程序没有使用共享变量或引用之类的话,可以使用detch函数,分离线程。
但是使用join可能会造成性能损失,因为原始线程要等待新线程的完成,所以有些情况(前提是你知道这种情况,如上)使用detch会更好。

上述代码如果主函数中的for循环发生异常,t.join就不会执行,因此需要注意线程安全

2、线程安全

    std::thread t(function_1);
    try
    {
        for (size_t i = 0; i < 100; i++)
        {
            std::cout << "from function main" << std::endl;
        }
        
    }
    catch (const std::exception&)
    {
        t.join();
    }
    t.join();
View Code

相关文章:

  • 2022-12-23
  • 2021-09-20
  • 2021-08-26
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-06-09
  • 2022-12-23
  • 2022-12-23
  • 2022-01-13
  • 2021-08-19
相关资源
相似解决方案