gpt4 book ai didi

c++ - 尝试显示我的线程的优先级时出现段错误

转载 作者:行者123 更新时间:2023-11-30 02:04:24 28 4
gpt4 key购买 nike

我创建了两个线程,我想在创建后查看它们的优先级:-为此,我编写了以下代码:-

   #include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <sched.h>
#include <string.h>
#include <errno.h>
int main()
{ //something
struct sched_param main_param, t1_param, t2_param;
pthread_t t1, t2;
int *sched1, *sched2;
if (pthread_create(&t1, NULL, fn1, NULL) != 0) // inside fn1 thread sleeps in loop
{
std::cout << "couldn't create t1" << std::endl;
return -1;
}
if (pthread_create(&t2, NULL, fn2, NULL) != 0) //inside fn2 thread sleeps in loop
{
std::cout << "couldn't create t2" << std::endl;
return -1;
}

if (pthread_getschedparam(t1, sched1, &t1_param) != 0)
{
std::cout << "error setting priority for T1: (" << errno << "), " <<
strerror(errno) << std::endl;
}
std::cout << "t1 thread will have a prio of " << t1_param.sched_priority << std::endl;
if (pthread_getschedparam(t1, sched2, &t1_param) != 0)
{
std::cout << "error setting priority for T1: (" << errno << "), " <<
strerror(errno) << std::endl;
}
std::cout << "t2 thread will have a prio of " << t2_param.sched_priority <<std::endl;

// something
}

只有当我添加与 pthread_getschedparam 相关的代码时,我才会遇到段错误,否则代码工作正常。我在这里做错了什么吗?我什至尝试用 NULL

替换 arhument sched1sched2

最佳答案

您声明了类型为 int* 的指针 sched1sched2 但从未初始化这些指针。您需要分配 int 变量,然后将指针传递给这些变量。

像这样:

int sched1, sched2;
.....
if (pthread_getschedparam(t1, &sched1, ....

关于c++ - 尝试显示我的线程的优先级时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10703121/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com