线程学习四:连接和分离线程

1.std::thread方法

在声明一个std::thread对象之后,都可以使用detach和join函数来启动被调线程,区别在于两者是否阻塞主调线程。

(1)当使用join()函数时,主调线程阻塞,等待被调线程终止,然后主调线程回收被调线程资源,并继续运行;

(2)当使用detach()函数时,主调线程继续运行,被调线程驻留后台运行,主调线程无法再取得该被调线程的控制权。当主调线程结束时,由运行时库负责清理与被调线程相关的资源。

实例

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

//初始化互斥锁,互斥锁只能同时被一个对象访问,如果同时有两个对访问,其中一个会被阻塞
void hello(char c)
{
    pthread_mutex_lock(&flock); // 上锁
    cout << c << ": ";
    for (int i = 0; i < 10; i++) {
        cout << i << " ";
    }
    cout << endl;
    pthread_mutex_unlock(&flock); // 解锁
}

int main()
{
    thread t0(hello, 'a');
    thread t1(hello, 'b');
    // 使用join(), 线程运行完, main函数才能结束。
    t0.join();
    t1.join();

    thread t2(hello, 'c');
    thread t3(hello, 'd');
    // 使用detach(), main函数不用等待线程结束才能结束。有时候线程还没运行完,main函数就已经结束了。如下的结果,d还没运行,main就结束了
    t2.detach();
    t3.detach();

/*结果1:
    a: 0 1 2 3 4 5 6 7 8 9
    b: 0 1 2 3 4 5 6 7 8 9
    c: 0 1 2 3 4 5 6 7 8 9
  结果2:
    a: 0 1 2 3 4 5 6 7 8 9 
    b: 0 1 2 3 4 5 6 7 8 9 
    d: 0 1 2 3 4 5 6 7 8 9
  ...结果...
*/
    return 0;
}

1.1 std::thread连接线程: join()

join()函数是一个等待线程完成函数,主线程需要等待子线程运行结束了才可以结束

1)谁调用了这个函数?调用了这个函数的线程对象,一定要等这个线程对象的方法(在构造时传入的方法)执行完毕后(或者理解为这个线程的活干完了!),这个join()函数才能得到返回。

2)在什么线程环境下调用了这个函数?上面说了必须要等线程方法执行完毕后才能返回,那必然是阻塞调用线程的,也就是说如果一个线程对象在一个线程环境调用了这个函数,那么这个线程环境就会被阻塞,直到这个线程对象在构造时传入的方法执行完毕后,才能继续往下走,另外如果线程对象在调用join()函数之前,就已经做完了自己的事情(在构造时传入的方法执行完毕),那么这个函数不会阻塞线程环境,线程环境正常执行。

实例:

#include <iostream>
#include <thread>
using namespace std;

void func1()
{
    std::cout << "i = ";
    for (int i = 0; i < 10; i++) {
        std::cout << i << " ";
    }
    std::cout << std::endl;
}

void func2()
{
    std::cout << "j = ";
    for (int j = 0; j < 10; j++) {
        std::cout << j << " ";
    }
    std::cout << std::endl;
}

int main() // 主线程
{
    thread t1(func1); // 子线程
    thread t2(func2); // 子线程
    cout << "*" << endl;
    cout << "**" << endl;
    cout << "***" << endl;
    t1.join(); 
    t2.join(); 
    // 等待上面两个子线程结束后才进入主线程
    cout << "****" << endl;
    return 0;
/*
结果1: 
*
**
***
j = 0 1 2 3 4 5 6 7 8 9 
i = 0 1 2 3 4 5 6 7 8 9 
****
结果2:
i = 0 1 2 3 4 5 6 7 8 9 
*
**
***
j = 0 1 2 3 4 5 6 7 8 9 
****
结果3/4/...: 
*/
}

结论:

两个线程的执行顺序不定,不是谁先join谁就先执行的。但是当使用了join()之后,程序是等待子线程结束之后才返回到主线程,然后结束进程的

1.1 std::thread分离线程: detach()

detach调用之后,目标线程就成为了守护线程,驻留后台运行,与之关联的std::thread对象失去对目标线程的关联,无法再通过std::thread对象取得该线程的控制权。当线程主函数执行完之后,线程就结束了,运行时库负责清理与该线程相关的资源。

当一个thread对象到达生命期终点而关联线程还没有结束时,则thread对象取消与线程之间的关联,目标线程线程则变为分离线程继续运行。

当调用join函数时,调用线程阻塞等待目标线程终止,然后回收目标线程的资源。

detach是使主线程不用等待子线程可以继续往下执行,但即使主线程终止了,子线程也不一定终止。

实例:

#include <iostream>
#include <thread>
using namespace std;

void func1()
{
    cout << "i = ";
    for (int i = 0; i < 10; i++)
    {
        cout << i << " ";
    }
    cout << endl;
}

void func2()
{
    cout << "j = ";
    for (int j = 0; j < 10; j++)
    {
        cout << j << " ";
    }
    cout << endl;
}

int main() // 主线程
{
    thread t1(func1); // 子线程
    thread t2(func2); // 子线程
    cout << "*" << endl;
    cout << "**" << endl;
    cout << "***" << endl;
    t1.detach(); // 分离子线程
    t2.detach(); // 分离子线程
    cout << "****" << endl;

/*结果1:
*i = 0 1j =  02 
**
***
 3**** 4 5 6 7 
8 9 
8 9
结果2/3/...:
*/
    return 0;
}

结论:

调用了detach,子线程还没完成,主线程就结束了。两个子线程的顺序也不是谁先detach谁就先执行的

2.pthread方法

2.1 pthread连接线程: pthread_join()

有时候我们想在一个线程中等待另一个线程结束,pthread_join()则为我们提供了这个功能。例如,我们在main线程中创建了子线程,需要先等待子线程退出,最后才从main函数退出。代码如下:

实例:

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

// 涉及多参数传递给线程的,都需要使用结构体将参数封装后,将结构体指针传给线程
void* threadFun1(void *args)
{
    int arg = *(int *)args;
    printf("child thread, arg = %d\n", arg);

    printf("i = ");
    for (int i = 0; i < 100; i++) {
        printf("%d ", i);
    }
    printf("\n");
}

void* threadFun2(void *args)
{
    int arg = *(int *)args;
    printf("child thread, arg = %d\n", arg);

    printf("j = ");
    for (int j = 0; j < 100; j++) {
        printf("%d ", j);
    }
    printf("\n");
}

int main()
{
    pthread_t t1, t2;
    int m  = 1, n = 2;
    if (pthread_create(&t1, NULL, threadFun1, &m) != 0) {
        fprintf(stderr, "create thread 1 fail\n");
        exit(-1);
    }

    if (pthread_create(&t2, NULL, threadFun2, &n) != 0) {
        fprintf(stderr, "create thread 2 fail\n");
        exit(-1);
    }

    printf("********************************\n");

    if (pthread_join(t1, NULL) != 0) {
        fprintf(stderr, "thread join 1 fail\n");
        exit(-1);
    }
    if (pthread_join(t2, NULL) != 0) {
        fprintf(stderr, "thread join 2 fail\n");
        exit(-1);
    }

    printf("main thread exit\n");
    exit(0);
}
/* 结果1:
********************************
child thread, arg = 1
i = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 child thread, arg = 2
j = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 
main thread exit

结果2/3/...:
*/

// 编译: g++ -g test.cpp -o test -lpthread

结论:

两个子线程结束后,主线程才会接着往下执行(即打印"main thread exit"),两个子线程的顺序也不是谁先pthread_join先谁先完成的

2.1 pthread分离线程: pthread_detach()

与pthread_join()不同,pthread_detach()的作用是分离某个线程:被分离的线程终止后,系统能自动回收该线程占用的资源

实例:

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

// 涉及多参数传递给线程的,都需要使用结构体将参数封装后,将结构体指针传给线程
void* threadFun1(void *args)
{
    int arg = *(int *)args;
    printf("child thread, arg = %d\n", arg);

    printf("i = ");
    for (int i = 0; i < 100; i++) {
        printf("%d ", i);
    }
    printf("\n");
}

void* threadFun2(void *args)
{
    int arg = *(int *)args;
    printf("child thread, arg = %d\n", arg);

    printf("j = ");
    for (int j = 0; j < 100; j++) {
        printf("%d ", j);
    }
    printf("\n");
}

int main()
{
    pthread_t t1, t2;
    int m  = 1, n = 2;
    if (pthread_create(&t1, NULL, threadFun1, &m) != 0) {
        fprintf(stderr, "create thread 1 fail\n");
        exit(-1);
    }

    if (pthread_create(&t2, NULL, threadFun2, &n) != 0) {
        fprintf(stderr, "create thread 2 fail\n");
        exit(-1);
    }

    printf("********************************\n");

    if (pthread_detach(t1) != 0) {
        fprintf(stderr, "thread join 1 fail\n");
        exit(-1);
    }
    if (pthread_detach(t2) != 0) {
        fprintf(stderr, "thread join 2 fail\n");
        exit(-1);
    }

    printf("main thread exit\n");
    exit(0);
}
/* 结果1:
child thread, arg = 1
i = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 
********************************
main thread exit
child thread, arg = 2
child thread, arg = 2

结果2/3/...:
*/

// 编译: g++ -g test.cpp -o test -lpthread

结论:

调用了pthread_detach,子线程还没完成,主线程就结束了。两个子线程的顺序也不是谁先pthread_detach谁就先执行的

总结

综上,pthread_join()和pthread_detach()的区别就是:

1. pthread_join()是阻塞式的,线程A连接(join)了线程B,那么线程A会阻塞在pthread_join()这个函数调用,直到线程B终止

2. pthread_detach()是非阻塞式的,线程A分离(detach)了线程B,那么线程A不会阻塞在pthread_detach(),pthread_detach()会直接返回,线程B终止后会被操作系统自动回收资源

注意

需要注意的是一个线程被detach后就不能被join了

来自于
https://blog.csdn.net/weixin_44862644/article/details/115765250
https://blog.csdn.net/zhwenx3/article/details/82229509

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

欢迎关注

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

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

    线程学习四:连接和分离线程

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

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

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

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

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

相关推荐