【Linux】盘点<多线程控制>基本操作&演示:创建&中止&等待&分离

前言

大家好吖,欢迎来到 YY 滴Linux系列 ,热烈欢迎! 本章主要内容面向接触过C++的老铁
主要内容含:
在这里插入图片描述

欢迎订阅 YY滴C++专栏!更多干货持续更新!以下是传送门!

一.POSIX线程库

  1. 与线程有关的函数构成了一个完整的系列,绝大多数函数的名字都是以“pthread_”打头的
  2. 要使用这些函数库,要通过引入头文件 include <pthread.h>
  3. 链接这些线程函数库时要使用编译器命令的“-lpthread”选项
gcc test.c -o test.o -lpthread

二.线程控制

1.pthread_t是什么类型

  • pthread_t 的类型取决于实现。对于Linux目前实现的NPTL实现而言,pthread_t类型的线程ID,本质
    就是一个进程地址空间上的一个地址。
    在这里插入图片描述

2.创建线程:pthread_create

【1】基本语法

功能:创建一个新的线程
原型
    int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg);
参数
    thread:返回线程ID
    attr:设置线程的属性,attr为NULL表示使用默认属性
    start_routine:是个函数地址,线程启动后要执行的函数
    arg:传给线程启动函数的参数
返回值:
    成功返回0;失败返回错误码

【2】示例演示

  • 创建完后,新线程执行rout函数去了,传入参数是NULL;
  • 主线程继续往下跑
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
void *rout(void *arg) {
    int i;
    for( ; ; ) {
    printf("I'am thread 1\n");
    sleep(1);
  }
}
int main( void )
{
    pthread_t tid;
    int ret;
    if ( (ret=pthread_create(&tid, NULL, rout, NULL)) != 0 ) {
        fprintf(stderr, "pthread_create : %s\n", strerror(ret));
        exit(EXIT_FAILURE);
    }
    int i;
    for(; ; ) {
        printf("I'am main thread\n");
        sleep(1);
    }
}

3.线程终止:pthread_exit&pthread_cancel

【1】基本语法

pthread_exit
功能:线程终止
原型
    void pthread_exit(void *value_ptr);
参数
    value_ptr:value_ptr不要指向一个局部变量。
返回值:
    无返回值,跟进程一样,线程结束的时候无法返回到它的调用者(自身)

pthread_cancel
功能:取消一个执行中的线程
原型
    int pthread_cancel(pthread_t thread);
参数
    thread:线程ID
返回值:
    成功返回0;失败返回错误码

【2】示例演示

// 线程函数  
void* thread_function(void* arg) {  
    int num_seconds = *((int*)arg);  
    printf("Thread is running. Will sleep for %d seconds.\n", num_seconds);  
    sleep(num_seconds);  // 休眠一段时间以模拟工作  
    printf("Thread has finished execution.\n");  
    pthread_exit(NULL); // 退出线程  
}  
  
int main() {  
    pthread_t thread;  
    int num_seconds = 5;  
    int* arg = &num_seconds;  
  
    // 创建线程  
    if (pthread_create(&thread, NULL, thread_function, (void*)arg) != 0) {  
        perror("Failed to create thread");  
        exit(EXIT_FAILURE);  
    }  
  
    // 等待线程完成  
    if (pthread_join(thread, NULL) != 0) {  
        perror("Failed to join thread");  
        exit(EXIT_FAILURE);  
    }  
  
    printf("Main thread has finished.\n");  
    return 0;  
}

4.线程等待:pthread_join

【1】为什么要进行线程等待

  • 为什么需要线程等待?——主线程等待其他线程
  1. 已经退出的线程,其空间没有被释放,仍然在进程的地址空间内。
  2. 创建新的线程不会复用刚才退出线程的地址空间

【2】基本语法

功能:等待线程结束
原型
int pthread_join(pthread_t thread, void **value_ptr);
参数
    thread:线程ID
    value_ptr:它指向一个指针,后者指向线程的返回值(没有返回值就填NULL)
返回值:
    成功返回0;失败返回错误码

【3】示例演示

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

void *thread1( void *arg )
{
    printf("thread 1 returning ... \n");
    int *p = (int*)malloc(sizeof(int));
    *p = 1;
    return (void*)p;
}

int main( void )
{
    pthread_t tid;
    void *ret;

    pthread_create(&tid, NULL, thread1, NULL);
    pthread_join(tid, &ret);
    //    pthread_join(tid, NULL);没有返回值就填NULL
    printf("thread return, thread id %X, return code:%d\n", tid, *(int*)ret);
    free(ret);

return 0;
}

5.线程分离:pthread_detach

【1】为什么要进行线程分离&线程joinable状态与分离状态

  • 默认情况下,新创建的线程是 joinable 的,线程退出后,需要对其进行pthread_join操作,否则无法释放资源,从而造成系统泄漏。
  • 如果不关心线程的返回值,join是一种负担,这个时候,我们可以告诉系统,当线程退出时, 自动释放线程资源 ,此时就是 分离状态

注意:

  • joinable和分离是冲突的,一个线程不能既是joinable又是分离的

【2】基本语法

-- 线程组内其他线程对目标线程进行分离
int pthread_detach(pthread_t thread);
-- 线程内自己分离
pthread_detach(pthread_self());

【3】示例演示

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
void *thread_run( void * arg )
{
    pthread_detach(pthread_self());//线程内自己分离,进入分离状态
    printf("%s\n", (char*)arg);
    return NULL;
}
int main( void )
{
    pthread_t tid;
    if ( pthread_create(&tid, NULL, thread_run, "thread1 run...") != 0 ) {
       printf("create thread error\n");
       return 1;
    }
    //不需要调用 pthread_join
    int ret = 0;
    return ret;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

YY的秘密代码小屋

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

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

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

打赏作者

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

抵扣说明:

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

余额充值