线程学习七:几个例子


目录
  • 1. 主线程中创建2个子线程,子线程按顺序执行 && 主线程比子线程结束晚
  • 2. 主线程中创建2个与主线程分离的子线程,并且等2个子线程结束后,主线程继续进行

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

// 在子线程中通过join()方法指定顺序
#include 
#include 
#include 
// 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 
#include 
#include 
// 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,那么会出现主线程结束,而子线程没有处理完成