线程学习七:几个例子

1. 主线程中创建2个子线程,子线程按顺序执行 && 主线程比子线程结束晚

// 在子线程中通过join()方法指定顺序
#include <iostream>
#include <thread>
#include <chrono>
// C++里处理多线程的头文件是thread
using namespace std;

class Test
{
public:
    Test() {}
    ~Test() {}

    void init(int m);

    void printValue() { cout << "m_iNum = " << m_iNum << endl; }
private:
    int m_iNum;
    thread m_t1;
    thread m_t2;
};

// 在类Test中创建两个子线程m_t1,m_t2,要求m_t2必须在m_t1完成后才能做处理
void Test::init(int m)
{
    m_iNum = m;
    m_t1 = thread([this]() {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        m_iNum++; // this->m_iNum

    });

    m_t2 = thread([this]() {
        m_t1.join();
        m_iNum *= 2;
        cout << "t2, m = " << m_iNum << endl; // this->m_iNum
    });

    m_t2.join();
}

int main()
{
    Test test;
    test.init(1);
    test.printValue();
}

2. 主线程中创建2个与主线程分离的子线程,并且等2个子线程结束后,主线程继续进行

#include <iostream>
#include <thread>
#include <chrono>
// C++里处理多线程的头文件是thread
using namespace std;

pthread_barrier_t barrier;

class Test
{
public:
    Test() {}
    ~Test() {}

    void init();

private:
    int m_iNum;

};

void Test::init()
{

    thread t1([this]() {
        std::this_thread::sleep_for(std::chrono::seconds(1));

        cout << "--------- t1 ---------" << endl;

        pthread_barrier_wait(&barrier);
    });

    thread t2 ([this]() {
        std::this_thread::sleep_for(std::chrono::seconds(1));

        cout << "--------- t2 ---------" << endl;

        pthread_barrier_wait(&barrier);
    });

    t1.detach();
    t2.detach();

}


int main()
{
    pthread_barrier_init(&barrier, NULL, 3);
    cout << "main start" << endl;

    Test test;
    test.init();

    pthread_barrier_wait(&barrier);
    pthread_barrier_destroy(&barrier);
    cout << "main end" << endl;
    return 0;
}

/*结果1:
main start
--------- t1 ---------
--------- t2 ---------
main end

 结果2:
main start
--------- t2 ---------
--------- t1 ---------
main end

 结果3/4/...:
*/

// 如果两个子线程中不加pthread_barrier_wait,那么会出现主线程结束,而子线程没有处理完成

原文链接: https://www.cnblogs.com/vivian187/p/15964513.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    线程学习七:几个例子

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/396708

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月7日 上午9:08
下一篇 2023年4月7日 上午9:08

相关推荐