Unix/C/C++进阶--pthread_creat return 1失败

  • 1 介绍
    • 1.1 man pthread_create
    • 1.2 一般失败原因
    • 1.3 最大进程/线程数(理论)
    • 1.3 最大进程/线程数(实际)
    • 1.4 查看Linux实际运行的总线程数
    • 1.5 查看运行的进程
    • 1.6 查看进程信息
    • 1.7 top -H 一行显示一个线程
    • 1.8 top -Hp pid 查看进程信息(资源暂用、线程状态)
    • 1.9 ulimits -s 查看默认栈空间
  • 2 问题描述
  • 3 问题分析
  • 4 解决方案
    • 4.1 service 中删除Delegate=yes
    • 4.2 向rt_runtime_us文件中写入数据
  • 参考

1 介绍

1.1 man pthread_create

PTHREAD_CREATE(3)                                                                     Linux Programmer's Manual                                                                     PTHREAD_CREATE(3)NAMEpthread_create - create a new threadSYNOPSIS#include <pthread.h>int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);Compile and link with -pthread.DESCRIPTIONThe pthread_create() function starts a new thread in the calling process.  The new thread starts execution by invoking start_routine(); arg is passed as the sole argument of start_routine().The new thread terminates in one of the following ways:* It calls pthread_exit(3), specifying an exit status value that is available to another thread in the same process that calls pthread_join(3).* It returns from start_routine().  This is equivalent to calling pthread_exit(3) with the value supplied in the return statement.* It is canceled (see pthread_cancel(3)).* Any of the threads in the process calls exit(3), or the main thread performs a return from main().  This causes the termination of all threads in the process.The  attr  argument  points  to  a  pthread_attr_t  structure  whose contents are used at thread creation time to determine attributes for the new thread; this structure is initialized usingpthread_attr_init(3) and related functions.  If attr is NULL, then the thread is created with default attributes.Before returning, a successful call to pthread_create() stores the ID of the new thread in the buffer pointed to by thread; this identifier is used to refer to the thread in subsequent callsto other pthreads functions.The  new  thread  inherits a copy of the creating thread's signal mask (pthread_sigmask(3)).  The set of pending signals for the new thread is empty (sigpending(2)).  The new thread does notinherit the creating thread's alternate signal stack (sigaltstack(2)).The new thread inherits the calling thread's floating-point environment (fenv(3)).The initial value of the new thread's CPU-time clock is 0 (see pthread_getcpuclockid(3)).Linux-specific detailsThe new thread inherits copies of the calling thread's capability sets (see capabilities(7)) and CPU affinity mask (see sched_setaffinity(2)).RETURN VALUEOn success, pthread_create() returns 0; on error, it returns an error number, and the contents of *thread are undefined.ERRORSEAGAIN Insufficient resources to create another thread.EAGAIN A system-imposed limit on the number of threads was encountered.  There are a number of limits that may trigger this error:  the  RLIMIT_NPROC  soft  resource  limit  (set  via  setr‐limit(2)),  which  limits  the  number  of processes and threads for a real user ID, was reached; the kernel's system-wide limit on the number of processes and threads, /proc/sys/ker‐nel/threads-max, was reached (see proc(5)); or the maximum number of PIDs, /proc/sys/kernel/pid_max, was reached (see proc(5)).EINVAL Invalid settings in attr.

1.2 一般失败原因

EAGAIN 创建线程时,资源数不足,或者是遇到了系统对线程数量的限制
EINVAL arrt 中使用了无效参数
EPERM 系统不允许设置调度策略 和 在attr中使用特定的参数

EPERM的定义,在 erron.h 头文件中的定义,就是1

1.3 最大进程/线程数(理论)

以imx6为例:

cat /proc/sys/kernel/pid_max
32768

可以使用ulimit –u 查看系统限制某用户最大可以运行多少线程max_user_process

ulimit -u 65535
sysctl -w kernel.pid_max=65535

1.3 最大进程/线程数(实际)

理论上linux 上最大线程数是 = 总虚拟内存(用户空间) / 线程栈大小;

一般32bit PC机系统上,进程空间是4G,其中0—3G 是用户空间,3G —4G 是内核空间,所以理论上最大线程数 = 3*1024/ 8M = 384个,考虑系统主线程占用情况,故可创建的最大线程大概为 384 个;如何进程或者线程占用的栈空间小于8M,实际能创建更多的进程/线程。

1.4 查看Linux实际运行的总线程数

ps -eL | wc –l
176

1.5 查看运行的进程

所有:
ps auxUSER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.3   5480  3708 ?        Ss   May20   0:04 /sbin/init
root         2  0.0  0.0      0     0 ?        S    May20   0:00 [kthreadd]
root         3  0.1  0.0      0     0 ?        R    May20   2:32 [ksoftirqd/0]
root         4  0.1  0.0      0     0 ?        S    May20   1:48 [ktimersoftd/0]
root         6  0.0  0.0      0     0 ?        S<   May20   0:00 [kworker/0:0H]
root         7  0.0  0.0      0     0 ?        S    May20   0:00 [kworker/u8:0]
root         8  0.0  0.0      0     0 ?        S    May20   0:36 [rcu_preempt]
root         9  0.0  0.0      0     0 ?        S    May20   0:00 [rcu_sched]
root        10  0.0  0.0      0     0 ?        S    May20   0:00 [rcu_bh]筛选:
ps aux | grep 某进程名root     18741  0.0  0.2   3832  2248 pts/0    Sl   07:41   0:00 ./ubase

1.6 查看进程信息

打印信息中Threads后面就是线程数量。

cat /proc/{pid}/statusName:   ubase
State:  S (sleeping)
Tgid:   18741
Ngid:   0
Pid:    18741
PPid:   9740
TracerPid:      0
Uid:    0       0       0       0
Gid:    0       0       0       0
FDSize: 256
Groups: 0
VmPeak:     3832 kB
VmSize:     3832 kB
VmLck:         0 kB
VmPin:         0 kB
VmHWM:      2248 kB
VmRSS:      2248 kB
VmData:      716 kB
VmStk:       136 kB
VmExe:        92 kB
VmLib:      2512 kB
VmPTE:        14 kB
VmPMD:         0 kB
VmSwap:        0 kB
Threads:        2
SigQ:   0/5431
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: 0000000000000000
SigIgn: 0000000000000000
SigCgt: 0000000180000000
CapInh: 0000000000000000
CapPrm: 0000003fffffffff
CapEff: 0000003fffffffff
CapBnd: 0000003fffffffff
Cpus_allowed:   f
Cpus_allowed_list:      0-3
Mems_allowed:   1
Mems_allowed_list:      0
voluntary_ctxt_switches:        206
nonvoluntary_ctxt_switches:     18

1.7 top -H 一行显示一个线程

top -H
top - 07:54:14 up 1 day,  2:29,  1 user,  load average: 0.42, 0.23, 0.17
Threads: 176 total,   1 running, 175 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.7 us,  2.0 sy,  0.0 ni, 97.3 id,  0.0 wa,  0.0 hi,  0.1 si,  0.0 st
KiB Mem :  1023424 total,   664420 free,   162856 used,   196148 buff/cache
KiB Swap:        0 total,        0 free,        0 used.   823124 avail MemPID USER      PR  NI    VIRT    RES    SHR S %CPU %MEM     TIME+ COMMAND
27866 root      20   0    5068   2344   1816 R  1.3  0.2   0:00.32 top1 root      20   0    5480   3708   2552 S  0.0  0.4   0:04.75 systemd2 root      20   0       0      0      0 S  0.0  0.0   0:00.01 kthreadd3 root      20   0       0      0      0 S  0.0  0.0   2:33.51 ksoftirqd/04 root      -2   0       0      0      0 S  0.0  0.0   1:49.58 ktimersoftd/06 root       0 -20       0      0      0 S  0.0  0.0   0:00.00 kworker/0:0H7 root      20   0       0      0      0 S  0.0  0.0   0:00.07 kworker/u8:08 root      -2   0       0      0      0 S  0.0  0.0   0:37.30 rcu_preempt9 root      -2   0       0      0      0 S  0.0  0.0   0:00.00 rcu_sched10 root      -2   0       0      0      0 S  0.0  0.0   0:00.00 rcu_bh11 root      -2   0       0      0      0 S  0.0  0.0   0:00.00 rcub/012 root      -2   0       0      0      0 S  0.0  0.0   0:49.81 rcuc/013 root      20   0       0      0      0 S  0.0  0.0   0:00.00 kclksetdelayd14 root      rt   0       0      0      0 S  0.0  0.0   0:00.00 posixcputmr/015 root      20   0       0      0      0 S  0.0  0.0   0:00.00 kcmosdelayd16 root      rt   0       0      0      0 S  0.0  0.0   0:07.62 migration/017 root      rt   0       0      0      0 S  0.0  0.0   0:07.22 migration/118 root      -2   0       0      0      0 S  0.0  0.0   1:13.46 rcuc/1

1.8 top -Hp pid 查看进程信息(资源暂用、线程状态)

 top -Hp 18741top - 07:57:10 up 1 day,  2:32,  1 user,  load average: 0.09, 0.16, 0.14
Threads:   2 total,   0 running,   2 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.7 us,  2.5 sy,  0.0 ni, 96.6 id,  0.2 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem :  1023424 total,   664040 free,   163208 used,   196176 buff/cache
KiB Swap:        0 total,        0 free,        0 used.   822776 avail MemPID USER      PR  NI    VIRT    RES    SHR S %CPU %MEM     TIME+ COMMAND
18741 root      20   0    3832   2248   2100 S  0.0  0.2   0:00.03 ubase
18743 root      -2   0    3832   2248   2100 S  0.0  0.2   0:00.00 Can0_Motor

1.9 ulimits -s 查看默认栈空间

8192KB(8M)

ulimits -s
8192

2 问题描述

在Linux系统 ubuntu16.04 中,ssh进去,root下,运行进程,pthread_create实时线程创建失败,返回1。

3 问题分析

EPERM的定义,在 erron.h 头文件中的定义,就是1。从解释看,就是说没有权限来设置调度策略及参数定义。
systemd默认将ssh连接放到一个非rt组中,如果试图ssh并运行FIFO/RR任务,它将不起作用。您需要将shell移到允许优先级调度的默认cpu:/ group中。
cgclass -g cpu:/ $$
如果你把ControlGroup=cpu:/放在[service]下,你的systemd单元文件可以启动你的服务并获得优先级调度。

from:https://github.com/coreos/bugs/issues/410

what may or may not be very related, systemd defaults put ssh connections into a non-RT cgroup. if you're trying to ssh in and run FIFO/RR tasks, it just won't work. you need to move your shell into the default cpu:/ group which does permit priority scheduling.cgclassify -g cpu:/ $$your systemd unit file can start your service and get priority scheduling if you put ControlGroup=cpu:/ under [Service]

4 解决方案

4.1 service 中删除Delegate=yes

cat lib/systemd/system/user@.service
将Delegate=yes注释掉,就可以了。

4.2 向rt_runtime_us文件中写入数据

向rt_runtime_us文件中写入数据950000。
echo 950000 > /sys/fs/cgroup/cpu,cpuacct/user.slice/cpu.rt_runtime_us
echo 950000 > /sys/fs/cgroup/cpu,cpuacct/user.slice/user-0.slice/cpu.rt_runtime_us
echo 950000 > /sys/fs/cgroup/cpu,cpuacct/user.slice/user-0.slice/session-c1.scope/cpu.rt_runtime_us

参考

1、
2、pthread_create priority thread returns EPERM when run as root
3、Linux pthread_creat() 创建线程失败问题总结
4、Linux创建实时线程失败 (pthread_create SCHED_RR 失败)
5、pthread_create返回值

Unix/C/C++进阶--线程 pthread_creat() return 1失败相关推荐

  1. UNIX环境高级编程——线程

    线程包含了表示进程内执行环境必需的信息,其中包括进程中标示线程的线程ID.一组寄存器值.栈.调度优先级和策略.信号屏蔽字.errno变量以及线程私有数据. 进程的所有信息对该进程的所有线程都是共享的, ...

  2. android jni 多线程,[Android]JNI进阶--线程池

    当一些异步的任务的时候,使用C++来创建线程来做任务的时候, 可以引用std::thread这个库 使用方法如下,创建一个线程,里面通过std::bind来绑定方法任务. std::thread th ...

  3. UNIX环境高级编程——线程同步之条件变量以及属性

    条件变量变量也是出自POSIX线程标准,另一种线程同步机制.主要用来等待某个条件的发生.可以用来同步同一进程中的各个线程.当然如果一个条件变量存放在多个进程共享的某个内存区中,那么还可以通过条件变量来 ...

  4. java进阶 线程池 join用法总结:thread4.join();方法,就表明thread4.join();这个线程受到贵客待遇,直到这个线程执行完,被插入这个方法的载体线程才可以执行。

    那个线程调用join 举例 thread4.join();方法,就表明thread4.join();这个线程受到贵客待遇,直到这个线程执行完,被插入这个方法的载体线程才可以执行. package ja ...

  5. unix环境高级编程-线程(2)

    线程终止: 如果进程中的任意线程调用了exit._Exit或者_exit,那么整个进程就会终止,与此类似,如果默认的动作是终止进程,那么发送到线程的信号就会终止整个进程 单个进程可以通过三种方式退出, ...

  6. Unix/Linux IPC及线程间通信总结

    一.互斥与同步 1.互斥:是指某一资源同时只允许一个访问者对其进行访问,具有唯一性和排它性.但互斥无法限制访问者对资源的访问顺序,即访问是无序的. 2.同步:是指在互斥的基础上(大多数情况),通过其它 ...

  7. UNIX网络编程——使用线程的TCP回射服务器程序

    同一进程内的所有线程除了共享全局变量外还共享: (1)进程指令: (2)大多数数据: (3)  打开的文件(即描述符): (4)信号处理函数和信号处置: (5)当前工作目录: (6)用户ID和组ID. ...

  8. java线程池newfi_Java进阶——线程与多线程

    线程和多线程 概念 程序 程序是一段静态代码. 进程 进程是程序的一次动态执行过程(从代码加载.执行.执行完毕的完整过程).进程是资源分配的最小单位. 线程 线程是CPU调度的最小执行单位.程序执行过 ...

  9. 『Java练习生的自我修养』java-se进阶³ • 线程的等待与唤醒

    ☕☕ Java进阶攻坚克难,持续更新,一网打尽IO.注解.多线程-等java-se进阶内容.

  10. UNIX(多线程):27---多线程并发之原子操作与无锁编程

    原子操作:顾名思义就是不可分割的操作,该操作只存在未开始和已完成两种状态,不存在中间状态: 原子类型:原子库中定义的数据类型,对这些类型的所有操作都是原子的,包括通过原子类模板std::atomic& ...

最新文章

  1. 【PC工具】windows批处理脚本一键bat脚本编辑器,bat转exe工具使用方法,附helloworld参考例程...
  2. 时下最热开源大数据技术TOP10
  3. BERT可以上几年级了?Seq2Seq“硬刚”小学数学应用题
  4. ValueError: XPath error: Invalid expression in //*[@id=‘info‘]/div/p[1]/test()_Python系列学习笔记
  5. 巧用apply让javascript函数仅执行一次
  6. AgileEAS.NET敏捷开发平台案例-药店系统-项目说明
  7. 虾米回应“关闭”消息:不予置评;明年 Win 10 或将原生运行安卓应用;Perl 项目治理新规| 极客头条...
  8. php常见问题辨析(二)
  9. CIO如何做好灾难恢复/数据外泄的业务连续性计划?
  10. Redis客户端工具如何连接宝塔Redis服务器
  11. 伺服速度控制模式接线图_伺服驱动器控制模式的接线及其注意事项
  12. 南大周志华、俞扬、钱超最新力作:演化学习:理论与算法进展一书导读
  13. android 对称加密完毕,通过 Android keystore 和 fingerprint 结合实现数据加密和解密
  14. Python 入门-Task1 变量、运算符、数据类型及位运算
  15. Python操作Excel(一)
  16. 【LeetCode343】剪绳子(动态规划)
  17. 【kali-漏洞利用】(3.4)免杀Payload 生成工具(上):Veil安装、启动、Can‘t find the WINE profile问题
  18. VBA SolidWorks 二次开发 API ---从宏开始
  19. Hold不住的老师 HNUST 1588
  20. ae学习笔记(粒子爱心教程笔记)

热门文章

  1. 前端将dom转换为png、html、pdf并实现下载功能
  2. 3D打印+粉末冶金,打开碳化硅反射镜轻量一体化制造大门
  3. ECRS软件解析:标准工时是怎么计算的?如何计算标准工时?
  4. GIS的VR支持:CityEngine如何通过Unity支持HTC Vive?
  5. RecyclerView布局靠左问题
  6. delphi开发对接抖音团购码核销(一)申请
  7. A version of this package for your version of R might be avai7ab1e elsewhere,
  8. 笔记-商务与经济统计 第2章 描述统计学 I:表格法和图形法
  9. 软件测试 | 测试开发 | 什么是流程管理平台?
  10. 【青梅快讯】Greenplum关键组件版本更新:GPSS 1.6.0和GPCC 6.5已发布