gpt4 book ai didi

c - timer_create 是否为处理程序创建新线程

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

timer_settime() 每秒建立一个计时器。信号处理程序是 traffic_measurement_handlertraffic_measurement_handler 是否在新线程中运行?如何在处理程序运行时让 callback 停止?

#define CLOCKID CLOCK_REALTIME
#define SIG SIGUSR1
timer_t timerid;

int main(void)
{
..

build_timer();
pcap_loop(pcap_handle, -1, callback, NULL);
}

void callback() // callback of Libpcap API: pcap_loop()
{
detect_network_traffic(); // stop when timer expires, and then continue
// to run when traffic_measurement_handler has finished.
}

// timer handler runs every second to update database
void traffic_measurement_handler()
{
.. // This block will fetch global variables, so I want to
// let callback stop when this handler is running.


// rebuild the timer
build_timer();

}

// set timer
void build_timer()
{
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = traffic_measurement_handler;
sigemptyset(&sa.sa_mask);
sigaction(SIG, &sa, NULL);

sev.sigev_notify = SIGEV_SIGNAL;
sev.sigev_signo = SIG;
sev.sigev_value.sival_ptr = &timerid;
timer_create(CLOCKID, &sev, &timerid);

its.it_value.tv_sec = 1;
its.it_value.tv_nsec = 0;
its.it_interval.tv_sec = its.it_value.tv_sec;
its.it_interval.tv_nsec = its.it_value.tv_nsec;

timer_settime(timerid, 0, &its, NULL);
}

信号处理程序在只有一个线程的进程中安全吗?

添加:第二个版本
这样对吗?

pthread_t thread_global;

int main(void)
{
// register SIGUSR1 handler
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = traffic_measurement_handler;
sigemptyset(&sa.sa_mask);
sigaction(SIG, &sa, NULL);

pthread_create(&thread1, NULL, processing_thread, (void *) thread_id1);
pthread_create(&thread2, NULL, timer_thread, (void *) thread_id2);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
}

void *processing_thread(void *thread_id)
{
pcap_loop(pcap_handle, -1, callback, NULL);
}

void callback() // callback of Libpcap API: pcap_loop()
{
thread_global = pthread_self();
detect_network_traffic(); // stop when SIGUSR1 is caught, and then continue
// to run when traffic_measurement_handler has finished.
}

//update database every second when SIGUSR1 is caught
void traffic_measurement_handler()
{
..
}

//This thread is used to notify updating database every second.
void *timer_thread(void *thread_id)
{
for (; ;) {
sleep(1);
pthread_kill(thread_global, SIGUSR1);
}
}

最佳答案

  1. Does traffic_measurement_handler run in a new thread?

POSIX threadssigev_notify = SIGEV_SIGNAL 时,不会因为信号而创建新线程。因此,在您的代码中,您不会创建新线程。

  1. How to let callback stop when the handler is running?

您可以将信号设置为由运行回调的同一线程处理。

POSIX.1 distinguishes the notions of signals that are directed to the process as a whole and signals that are directed to individual threads.

阅读Unix pthreads and signals: per thread signal handlers

关于c - timer_create 是否为处理程序创建新线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42777964/

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