pthreads_create()返回非零值?

时间:2016-12-20 11:33:59

标签: c++ pthreads

我在调用pthread之前创建了一个设置pthread_create()属性的函数。但是,pthread_create()失败,因为它返回非零值。我不确定我的函数设置的属性有什么问题。我正在使用g++上的Ubuntu 16.04 LTS编译我的计划。

编译并执行我正在使用:

g++ example.cpp -lpthread
./a.out

-

typedef void *(*DART_TASK_T)(void *);
typedef void (*DART_CALLBACK_T)(int);

static struct taskcontrolblock_s sysTask[MAX_DARTOS_THREADS];
static unsigned max_task_id_registered = 0;

static std :: bitset<sizeInBytes(MAX_DARTOS_THREADS)> taskIDs;

struct taskcontrolblock_s {
    const char *name;

    DART_TASK_T routine;
    DART_CALLBACK_T cleanup_callback;

    void *arg;
    unsigned arg_len;

    union {
        uint8_t flags;
        struct {
        //uint8_t created:1;
        //uint8_t running:1;
        //uint8_t blocked:1;
        //uint8_t suspended:1;
        //uint8_t killed:1;
        //uint8_t completed:1;
        //uint8_t;
        }; 
    };

    int priority; 

    pthread_t thread;
}__attribute__((packed));


static int dispatch_task(int tid)
{
    if (!taskIDs[tid]) // 
        return -1;

    pthread_attr_t attr;
    struct sched_param param;
    param.sched_priority = sysTask[tid].priority;
    int policy = SCHED_RR;

    if (pthread_attr_init(&attr))
        return -1;
    if (pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED))
        return -1;
    if (pthread_attr_setschedpolicy(&attr, policy))
        return -1;
    if (pthread_attr_setschedparam(&attr, &param))
        return -1;
    if (pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM))
        return -1;

    if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED))
        return -1;

    if (pthread_create(&sysTask[tid].thread, &attr, sysTask[tid].routine, sysTask[tid].arg))
    return -1;

    pthread_attr_destroy(&attr);
    return 0;
}

修改

调用perror()会将字符数组Operation not permitted打印到stderr

以root权限运行程序解决了这个问题。

1 个答案:

答案 0 :(得分:2)

答案的第一部分是,要使用SCHED_RR,您的用户必须拥有CAP_SYS_NICE。如您所知,以root运行会使其正常运行。但只要您拥有CAP_SYS_NICE&#34;功能,您就可以像任何用户一样运行。&#34;获得此功能的一种方法是使用setcap,其解释如下:https://stackoverflow.com/a/37528755/4323

您需要能够运行sudo setcap