嵌入式(线程的创建和回收)

2023-11-16

线程的创建

 #include  <pthread.h>
 int  pthread_create(pthread_t *thread, const
       pthread_attr_t *attr, void *(*routine)(void *), void *arg);

成功返回0,失败时返回错误码
thread 线程对象
attr 线程属性,NULL代表默认属性
routine 线程执行的函数
arg 传递给routine的参数 ,参数是void * ,注意传递参数格式,

#include "stdio.h"
#include "pthread.h"
#include "unistd.h"

int* testThread(char *arg)
{
        printf("This is a thread test\n");
        return NULL;
}

int main()
{
        pthread_t tid;
        int ret;
        ret = pthread_create(&tid,NULL,(void *)testThread,NULL);
        printf("This is main thread\n");
        sleep(1);
}

编译错误分析:
1.

createP_t.c:14:36: warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type [-Wincompatible-pointer-types]
     ret = pthread_create(&tid,NULL,testThread,NULL);
                                    ^
In file included from createP_t.c:1:0:
/usr/include/pthread.h:233:12: note: expected ‘void * (*)(void *)’ but argument is of type ‘int * (*)(char *)

意义:表示pthread_create参数3的定义和实际代码不符合,期望的是void * (*)(void *) ,实际的代码是int * (*)(char *)
解决方法:改为pthread_create(&tid,NULL,(void)testThread,NULL);*

createP_t.c:(.text+0x4b):对‘pthread_create’未定义的引用
collect2: error: ld returned 1 exit status --------这个链接错误,
表示pthread_create这个函数没有实现
解决方法:编译时候加 -lpthread

注意事项:1. 主进程的退出,它创建的线程也会退出。
线程创建需要时间,如果主进程马上退出,那线程不能得到执行

线程退出函数 pthread_exit(NULL);

获取线程的id
通过pthread_create函数的第一个参数;通过在线程里面调用pthread_self函数

线程间参数传递:(重点难点)

编译错误:

createP_t.c:8:34: warning: dereferencing ‘void *’ pointer
     printf("input arg=%d\n",(int)*arg);
                                  ^
createP_t.c:8:5: error: invalid use of void expression
     printf("input arg=%d\n",(int)*arg);

错误原因是void *类型指针不能直接用*取值(*arg),因为编译不知道数据类型。
解决方法:转换为指定的指针类型后再用*取值 比如:*(int *)arg

1.通过地址传递参数,注意类型的转换
2.值传递,这时候编译器会告警,需要程序员自己保证数据长度正确

#include "stdio.h"
#include "pthread.h"
#include "unistd.h"

int* testThread(char *arg)
//void* testThread(void *arg)
{
        printf("This is a thread test\n");
        printf("%d\n",*arg);
//      printf("%d\n",(int)arg);
        printf("child pid=%d tid=%lu\n",getpid(),pthread_self());
        return NULL;
}

int main()
{
        pthread_t tid;
        int ret;
        char a=5;
        //int a=5;
        ret = pthread_create(&tid,NULL,(void *)testThread,(char*)&a);
        // ret = pthread_create(&tid,NULL,(void *)testThread,(void*)a);  
        //只要变量内存一致就可以传递,值传递在程序运行时不会被修改,地址传递可能出现线程还没运行,主程序就把地址修改了,导致传参错误。
        printf("This is main thread\n");
        printf("main tid%lu\n",tid);
        sleep(1);
}

运行错误:

*** stack smashing detected ***: ./mthread_t terminated

已放弃 (核心已转储)

原因:栈被破坏了(数组越界)
ps - eLf|grep xxx :线程查看命令

线程的回收:
使用pthread_join 函数:

#include  <pthread.h>
 int  pthread_join(pthread_t thread, void **retval);

注意:pthread_join 是阻塞函数,如果回收的线程没有结束,则一直等待

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

void  *testThread(void *arg)
{
     printf("This is child thread\n");
     sleep(5);
     pthread_exit("exit exit");
 }

int main()
 {
  pthread_t tid;
  void *ret;
  ret=pthread_create(&tid,NULL,testThread,NULL);
  pthread_join(tid,&ret);
  printf("Thread ret=%s\n",(char *)ret);
  sleep(1);
 }
This is child thread
Thread ret=exit exit

编译错误:
pjoin.c:13:5: error: unknown type name ‘pthead_t’
pthead_t tid;
错误类型:未知的类型pthead_t
错误可能:1拼写错误,2对应的头文件没有包含

pjoin.c:18:12: warning: format ‘%s’ expects argument of type ‘char *, but argument 2 has type ‘void *[-Wformat=]
     printf("thread ret=%s\n",retv);

错误类型:参数不匹配,期望的是char * ,但参数retv是void *
解决:在参数前面加强制类型转换(char*)retv

使用线程的分离(当回收join函数不方便时候用分离):

两种方式:
1 使用pthread_detach
2 创建线程时候设置为分离属性

  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
void *func(void *arg){
    printf("This is child thread\n");
    sleep(25);
    pthread_exit("thread return");
}

int main()
{
    pthread_t tid[100];
    void *retv;
    int i;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);

    for(i=0;i<100;i++)
    {
        pthread_create(&tid[i],&attr,func,NULL);
       // pthread_detach(tid);
    }
        while(1)
        {    
        	sleep(1);
      	} 
}


本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

嵌入式(线程的创建和回收) 的相关文章

随机推荐

  • Python编程基础之三对象

    一 简介 Python使用对象模型来存储数据 构造任何类型的值都是一个对象 再加上内建类型 标准类型运算符和内建函数 有助于更好的理解Python是如何工作的 二 详解 1 Python的对象 所有的 Python 对像都拥有三个特性 身份
  • Windows与网络基础22-数据封装与解封装

    数据的封装和解封装 目标 理解数据的封装与解封装过程 针对于一个简单的网络环境 能够独立讲解出网络传输过程 目录 一 数据封装过程 二 数据解封装过程 三 每一层对应的网络设备 四 简单网络数据封装解封装实例 一 数据封装过程 应用层 将原
  • 12、文件链接、磁盘阵列、文件系统、网络协议、数据封装过程

    一 文件链接 ln s 软链接 ln 硬链接 区别 1 软链接产生新的inode号 硬链接不产生新的inode号 ls i 看inode 2 源文件删除后 软链接文件不可以用 硬链接文件可用 3 软链接可以跨分区 硬链接不可以跨分区 4 不
  • 关于扫描二维码拒绝获取摄像头权限导致的错误解决方法

    这个问题烦了我2天 在网上查阅资料 也许是自己的理解错误 怎么改都不行 今天换了一种思维 解决了这个问题 废话不多说 先上代码 try mCameraManager openDriver catch IOException e e prin
  • ROS集成开发环境搭建【安装VScode】

    1 下载 注意 下载操作是在虚拟机中的Ubuntu中进行的 可以下载到 home 下载 文件夹中 vscode 下载链接 最新版本 Documentation for Visual Studio CodeFind out how to se
  • (c/c++)——STL

    文章目录 一 迭代器 iterator 二 容器 1 string 2 Vector 最常用 3 list 4 map 5 unordered map 6 queue 三 算法 1 for each 2 find if 3 sort 一 迭
  • 大数据毕业设计 人脸识别与疲劳检测系统 - python opencv 图像识别

    文章目录 0 前言 1 课题背景 2 Dlib人脸识别 2 1 简介 2 2 Dlib优点 2 3 相关代码 2 4 人脸数据库 2 5 人脸录入加识别效果 3 疲劳检测算法 3 1 眼睛检测算法 3 2 打哈欠检测算法 3 3 点头检测算
  • taro框架开发小程序经验总结

    最近这一年来 做了三个小程序 第一个小程序用的原生框架 所有的样式和js都要自己写 不好看还写得头疼死 写第二个小程序的时候正觉得VUE3流行 想熟悉一下VUE3 因此找到了taro框架 这个框架好不好我也无从分辨 暂时能用就行 一 搭建项
  • 手把手看监控--当不设置JVM-Xms时

    背景 运维埋的一个坑 在该应用上只配置留 Xmx 没有配置 Xms 表象 堆内存从0 2G开始 最大到0 8G 就开始执行GC 导致频繁GC 大致间隔1分钟 次 从下图左侧即可看到 解决 增加 Xms重新发版本 堆内存 GC间隔明显看着好多
  • 网关服务器性能,服务网关API路由导致的性能问题分析

    背景 酷家乐是从 16 年初开始进行服务化改造的 因为一些特殊原因 无法直接使用主流的dubbo 或 spring cloud 因此酷家乐研发团队在开源的基础上做了二次开发 迅速上线了一套定制型的微服务框架 和其他微服务框架类似 酷家乐自己
  • Python3中使用argparse模块解析命令行参数

    argparse是Python的一个标准模块 用于解析命令行参数 即解析sys argv中定义的参数 实现在 https github com python cpython blob main Lib argparse py argpars
  • vs2017,vs2019 无法连接到Web服务器“IIS Express”

    不知道啥原因 突然就不能访问了 我的解决方式 在项目的根目录下显示所有隐藏的文件 找到 vs文件夹 删除 重启项目 尝试运行 发现正常了 完 转载于 https www cnblogs com lishidefengchen p 11434
  • C++及模式设计系列

    1 博客 偶尔e网事 C http blog csdn net jackyvincefu article category 1501695 1 1 博客 wuzhekai1985 设计模式C 实现 http blog csdn net wu
  • Ubuntu 玩机笔记

    文章目录 键盘Fn无法切换功能键与多媒体键 永久生效 保持Typore旧版本 不自动更新 修改日期显示为英文 键盘Fn无法切换功能键与多媒体键 终端输入 echo 2 sudo tee sys module hid apple parame
  • CMAKE_INSTALL_PREFIX无效的解决方案

    今天写一段cmake脚本 使用了变量CMAKE INSTALL PREFIX 命令如下 SET CMAKE INSTALL PREFIX
  • 计算机复试练习题2

    1求1 2 20 include
  • zjy-easyinput文本框带按钮,uni-easyinput增强版

    一 zjy calendar简介 zjy calendar日历是对uniapp uni easyinput文本框的增强 支持文本框前后加按钮 二 使用方法 源使用说明 https uniapp dcloud net cn component
  • 功率和evm的关系_详解功率放大器PA设计指标

    PA指标分析 一 PA的工艺 PA的设计指标包括频率 带宽 功率 效率 线性度 甚至可能也要要求噪声 目前主要有两种工艺CMOS和GaAs CMOS工艺 比GaAs有优势的地方 主要是集成度和成本 所以但凡是要求效率 噪声 线性度等指标的放
  • STM32 以太网W5500

    文章目录 W5500简介 以太网接入方案 SPI读写访问 寄存器以及地址 源码以及配置 实现 TCP Server 三次握手过程 SPI 配置 网络相关函数 W5500简介 W5500 是一款全硬件 TCP IP 嵌入式以太网控制器 为嵌入
  • 嵌入式(线程的创建和回收)

    线程的创建 include