线程源码分析之attr.c(基于linuxthreads2.0.1)

attr.c是线程属性管理的实现。因为linuxthreads是通过创建一个进程的方式实现线程的,所以属性中支持设置调度的优先级,调度策略等(参考操作系统的实现)。该文件没有太多内容。具体作用在分析其他文件的时候再作分析。

#include <unistd.h>
#include "pthread.h"
#include "internals.h"
// 初始化线程属性结构体
int pthread_attr_init(pthread_attr_t *attr)
{
  attr->detachstate = PTHREAD_CREATE_JOINABLE;
  attr->schedpolicy = SCHED_OTHER;
  attr->schedparam.sched_priority = 0;
  attr->inheritsched = PTHREAD_EXPLICIT_SCHED;
  attr->scope = PTHREAD_SCOPE_SYSTEM;
  return 0;
}

int pthread_attr_destroy(pthread_attr_t *attr)
{
  return 0;
}
// 设置detach状态
int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate)
{
  if (detachstate < PTHREAD_CREATE_JOINABLE ||
      detachstate > PTHREAD_CREATE_DETACHED)
    return EINVAL;
  attr->detachstate = detachstate;
  return 0;
}

int pthread_attr_getdetachstate(const pthread_attr_t *attr, int *detachstate)
{
  *detachstate = attr->detachstate;
  return 0;
}
// 设置调度优先级的属性
int pthread_attr_setschedparam(pthread_attr_t *attr,
                               const struct sched_param *param)
{
  // 由系统提供的最大和最小优先级
  int max_prio = sched_get_priority_max(attr->schedpolicy);
  int min_prio = sched_get_priority_min(attr->schedpolicy);

  if (param->sched_priority < min_prio || param->sched_priority > max_prio)
    return EINVAL;
  attr->schedparam = *param;
  return 0;
}

int pthread_attr_getschedparam(const pthread_attr_t *attr,
                               struct sched_param *param)
{
  *param = attr->schedparam;
  return 0;
}

int pthread_attr_setschedpolicy(pthread_attr_t *attr, int policy)
{
  if (policy != SCHED_OTHER && policy != SCHED_FIFO && policy != SCHED_RR)
    return EINVAL;
  // SCHED_OTHER是分时调度,设置成非分时调度需要是超级用户
  if (policy != SCHED_OTHER && geteuid() != 0)
    return ENOTSUP;
  attr->schedpolicy = policy;
  return 0;
}

int pthread_attr_getschedpolicy(const pthread_attr_t *attr, int *policy)
{
  *policy = attr->schedpolicy;
  return 0;
}
// 调度策略来源于继承还是显示设置的
int pthread_attr_setinheritsched(pthread_attr_t *attr, int inherit)
{
  if (inherit != PTHREAD_INHERIT_SCHED && inherit != PTHREAD_EXPLICIT_SCHED)
    return EINVAL;
  attr->inheritsched = inherit;
  return 0;
}

int pthread_attr_getinheritsched(const pthread_attr_t *attr, int *inherit)
{
  *inherit = attr->inheritsched;
  return 0;
}
// 优先级的有效范围,PTHREAD_SCOPE_SYSTEM是和系统所有线程竞争,否则是和本进程内的其他线程竞争
int pthread_attr_setscope(pthread_attr_t *attr, int scope)
{
  switch (scope) {
  case PTHREAD_SCOPE_SYSTEM:
    attr->scope = scope;
    return 0;
  case PTHREAD_SCOPE_PROCESS:
    return ENOTSUP;
  default:
    return EINVAL;
  }
}

int pthread_attr_getscope(const pthread_attr_t *attr, int *scope)
{
  *scope = attr->scope;
  return 0;
}

本文分享自微信公众号 - 编程杂技(theanarkh)

原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。

原始发表时间:2019-10-07

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励