gpt4 book ai didi

c - 如果我们将 sigev_notify 用作 SIGEV_THREAD,为什么 timer_create 会生成线程

转载 作者:太空宇宙 更新时间:2023-11-04 01:48:31 27 4
gpt4 key购买 nike

根据 timer_create 函数,如果我们将 SIGEV_THREAD 用作 sigev_notify,那么每次到期都会创建新线程。但是为什么 timer_create 函数会生成新线程,在我的例子下面,

int main(){

printf ("My process ID %d", getpid ());

int status = 0;

timer_t timer_id;

memset (&timer_id, 0, sizeof (timer_t));

int j = 10;

struct itimerspec ts;

struct sigevent se;

se.sigev_notify = SIGEV_THREAD;

se.sigev_value.sival_int = j;

se.sigev_notify_function = timer_thread;

ts.it_value.tv_sec = 3;

ts.it_interval.tv_sec =0;

status = timer_create (CLOCK_REALTIME, &se, &timer_id);

printf ("timer_id is %ld\n",(long int)timer_id);

assert (!status && "Create timer");

status = timer_settime (timer_id, 0, &ts, 0);

assert (!status && "Set timer");

return 0;

}

在此特定进程 ID 中运行的线程数是两个,

PID SPID TTY 时间命令

9945 9945 点/20 00:00:18 timer_create

9945 9946 点/20 00:00:00 timer_create

如果我们使用 SIGEV_SIGNAL ,timer_create 不会创建线程。

请有人告诉我为什么在 timer_create 函数期间创建线程(如果我们使用 SIGEV_THREAD)......??

最佳答案

它需要一个辅助线程来满足SIGEV_THREAD 要求来调用另一个线程的回调,man sigevent :

SIGEV_THREAD

Notify the process by invoking sigev_notify_function "as if" it were the start function of a new thread. (Among the implementation possibilities here are that each timer notification could result in the creation of a new thread, or that a single thread is created to receive all notifications.) The function is invoked with sigev_value as its sole argument. If sigev_notify_attributes is not NULL, it should point to a pthread_attr_t structure that defines attributes for the new thread (see pthread_attr_init(3)).

如果您查看 timer_create 的 glibc 实现您可能会注意到它创建了一个线程来处理所有带有 SIGEV_THREAD 选项的计时器:

/* Create the helper thread.  */
pthread_once (&__helper_once, __start_helper_thread);

关于c - 如果我们将 sigev_notify 用作 SIGEV_THREAD,为什么 timer_create 会生成线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48498452/

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