简体   繁体   English

防止线程终止影响C中的父进程?

[英]Preventing thread termination from affecting parent process in C?

My goal is to create an event handling infrastructure that will allow for registration of callback functions and calls to such functions based on time. 我的目标是创建一个事件处理基础结构,该基础结构将允许注册回调函数以及基于时间的此类函数的调用。 Further, I plan to make the callback handler multithreaded as there are no restrictions on the type of callbacks, so a sequential architecture could cause unwanted blocking. 此外,我计划使回调处理程序成为多线程的,因为对回调的类型没有任何限制,因此顺序体系结构可能会导致不必要的阻塞。

From my research I found that if a thread experiences undefined behavior and is terminated (.ie with SIGSEGV) then the entire process exits - which is obviously undesirable. 从我的研究中,我发现如果线程遇到未定义的行为并被终止(即使用SIGSEGV),则整个过程都会退出-这显然是不希望的。

The question, then, is what options are there for ensuring thread independence? 那么问题是,有什么选择可以确保线程独立性? I do not think fork ing is a viable option in this case since the callbacks are not fully fledged programs, but rather simple routines to do various time-based tasks. 在这种情况下,我认为fork不是一个可行的选择,因为回调不是完全成熟的程序,而是执行各种基于时间的任务的简单例程。

Correct me if I'm wrong.. If you want time-based tasks, I highly recommend you to try semaphores to control thread. 如果我错了,请纠正我。如果您要执行基于时间的任务,强烈建议您尝试使用信号量来控制线程。

Block thread function like : 阻止线程功能,例如:

while(1){
    sem_wait(my_semaphore);
    code_that_needs_to_be_done_in_thread;
}

when you need your work in thread to be done just signal it from code whenever you want and howmany times you want: 当您需要完成线程中的工作时,只要有需要,就可以从代码中发出信号:

sem_post(my_semaphore);
...
other_code;
sem_post(my_semaphore);
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM