【问题标题】:New thread on invocation of timer_create()调用 timer_create() 的新线程
【发布时间】:2011-02-07 21:58:10
【问题描述】:

我正在研究如何在调用函数 timer_create() 时获取线程 ID。 我观察到每次调用 timer_create() 时,都会创建一个新线程(主进程的子线程)。我用 ps -eL|grep 验证了这一点

我需要在使用 timer_create 的程序中获得由 ps -eL 显示的相同 TID(子线程 ID)。 从下面的代码:如何在我的程序中获取 TID 18018?

我研究了所有帖子,每个帖子都提到在调用通知函数而不是调用 timer_create() 时创建了一个新线程。

非常感谢您的帮助!

代码:

SLGTRACER_DEFINE(testMain, "testMain");


timer_t audit_timer1;

void timeoutHandler(sigval_t info)
{
    slgInfo(testMain, "timeoutHandler invoked");

    slgInfo(testMain, "gettid() = %lu TESTMAIN", syscall(SYS_gettid));
    slgInfo(testMain, "getpid() = %d TESTMAIN", getpid());

}

int main(void)
{
    slgInfo(testMain, "testMain Invoked");


    struct sigevent evp1;
    evp1.sigev_notify = SIGEV_THREAD;
    evp1.sigev_value.sival_ptr = &audit_timer1;
    evp1.sigev_notify_function = timeoutHandler;
    evp1.sigev_notify_attributes = NULL;

    const int ERROR_BUFFER_SIZE = 50;


       slgInfo(testMain, "Before FIRST timer_create");
       sleep(30);


    // Create timer thread
    if (timer_create(CLOCK_REALTIME, &evp1, &audit_timer1) != 0)
    {
       // Character buffer for storing error message.
        char     errBuff[ERROR_BUFFER_SIZE];

        memset(errBuff, 0, ERROR_BUFFER_SIZE);

        slgError(testMain,
                    "timer_start create failed. Error = %s",
                    strerror_r(errno, errBuff, ERROR_BUFFER_SIZE));

        timer_delete(audit_timer1);
        bzero(&audit_timer1, sizeof(audit_timer1));
    }


       slgInfo(testMain, "After FIRST timer_create");
       sleep(30); 

    return 0;

}

 

bash-3.1# ps -eL|grep testM
16651 16651 pts/0    00:00:00 testMain
16651 18018 pts/0    00:00:00 testMain 
child thread with ID created by timer_create() = 18018

【问题讨论】:

    标签: c++ c linux multithreading


    【解决方案1】:

    未指定在调用超时处理程序之前是否存在线程。当然,符合要求的实现可以推迟线程的创建,直到计时器到期。看起来像 pid 的数字线程 id 的存在也是一个实现细节,你不应该使用它。

    您能解释一下您要完成的工作吗?当然有更好的方法...

    【讨论】:

    • 经过多次测试,发现调用timer_create()时创建了一个子线程。我正在尝试在我的程序中获取该线程 ID。我将使用该线程 ID 为该线程设置调度选项。
    • 是的,在timer_create()调用之后,timeoutHandler()调用之前存在线程。
    • @LinuxNewbie 如果这是您需要的,您可以将 pthread_attr_t 指定为 struct sigevent 的 sigev_notify_attributes 成员。这样,您可以使用例如 pthread_attr_setschedpolicy 设置的属性来初始化线程。您应该使用这些新信息更新/更改您的问题。
    • 查看 nos 的评论,了解做你想做的事情的正确方法。请注意,我的回答和对“实现细节”的引用是假设您要编写一个可在其他操作系统和未来 Linux 版本上运行的可移植程序,而不仅仅是具有当前实现细节的当前版本。
    • 感谢您的回复!实际上,我已经尝试过了,但它在调度选项中不起作用。它从主进程继承 sched 选项。我正在寻找的是获取为 timer_create() 创建的线程的 ID。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多