Linux——多线程的控制

Linux——线程的慨念及控制-优快云博客



前言

我们在上一篇博客中学习了单线程的基本控制,及创建、阻塞、终止等操作,这篇博客介绍多个线程的控制。 


一、线程函数的认识

1、基本函数的回顾

1、线程的创建pthread_create

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);

2、线程阻塞pthread_join

int pthread_join(pthread_t thread, void **retval);

3、线程退出pthread_exit

void pthread_exit(void *retval);

2、线程的分离pthread_detach

int pthread_detach(pthread_t thread);
  • 参数说明
    • thread:要分离的线程的标识符。
  • 返回值
    • 成功时返回 0。
    • 出错时返回错误码,可通过 perror 函数输出错误信息。
  • 含义
    • 当一个线程被创建时,它的状态默认是可连接的(joinable),这意味着另一个线程可以使用 pthread_join 函数来等待它的结束,并获取其返回值。而线程分离是将线程的状态设置为已分离(detached),这样就不需要其他线程来等待它结束,当线程结束时,其资源会自动被系统回收。
    • 分离的线程在结束时会自动释放资源,包括线程的堆栈和其他系统资源,而不需要主线程或其他线程调用 pthread_join 函数来回收。
    • 对于一些后台线程,例如日志记录线程、垃圾回收线程等,它们通常在程序的整个生命周期内持续运行,并且不需要主线程等待它们结束或获取它们的返回值。将这些线程设置为分离状态可以简化线程的管理,避免主线程在结束时因为没有调用 pthread_join 而产生资源泄漏。

通俗的说就是当我们主线程不需要等待子线程的返回值时,我们可以让主线程与次线程分离开,不让主线程等待子线程的退出。

代码样例

#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <vector>
#include <string>
using namespace std;

#define NUM 4

void *Threadroutine(void *args)
{
    int cnt = 0;
    while (true)
    {
        cout << (*((string *)args)).c_str() << endl;
        sleep(1);

        if ((cnt++) == 3)
        {
            break;
        }
    }
    cout<<(*((string *)args)).c_str()<<"运行完了"<<endl;
    return nullptr;
}
int main()
{
    vector<pthread_t> tids;
    for (int i = 0; i < NUM; i++)
    {
        string *name = new string("我是线程-" + to_string(i));
        pthread_t tid;
        tids.push_back(tid);
        pthread_create(&tids[i], nullptr, Threadroutine, name);

    }
        for (auto &
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

爱吃喵的鲤鱼

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

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

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

打赏作者

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

抵扣说明:

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

余额充值