pthread in nginx module
Maxim Dounin
mdounin at mdounin.ru
Tue Mar 9 13:34:34 UTC 2021
Hello!
On Tue, Mar 09, 2021 at 01:00:20AM -0500, klowd92 wrote:
> Hi Everyone,
>
> I am developing an nginx module.
> The module requires some background processing via thread when the server is
> running.
>
> I have written my module to use pthread.h
> I have attempted to spawn a thread during the init_module function
> (specified in ngx_module_t of the module)
> Unfortunately this thread is terminated after the init_module function is
> done. I need the thread to continue running indefinitely.
>
> I have also tried to create a thread during the init_process function, which
> also fails.
>
> nginx is compiled with threadpool and fileio support.
>
> Is it possible to have my module use pthread.h and run pthead_create() to
> have create threads during the execution of nginx, which stay alive throught
> the life of the program?
> My attempts all failed as soon as the module return execution the nginx, the
> threads are terminated.
While you should be able to create threads if implemented
properly, this is usually a bad idea. Quoting development guide
(http://nginx.org/en/docs/dev/development_guide.html#threads_pitfalls):
It is recommended to avoid using threads in nginx because it will
definitely break things: most nginx functions are not thread-safe.
It is expected that a thread will be executing only system calls
and thread-safe library functions. If you need to run some code
that is not related to client request processing, the proper way
is to schedule a timer in the init_process module handler and
perform required actions in timer handler. Internally nginx makes
use of threads to boost IO-related operations, but this is a
special case with a lot of limitations.
--
Maxim Dounin
http://mdounin.ru/
More information about the nginx
mailing list