libUPnP 1.14.19
Functions
ThreadPool.c File Reference
#include <sys/param.h>
#include "ThreadPool.h"
#include "FreeList.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Include dependency graph for ThreadPool.c:

Functions

static long DiffMillis (struct timeval *time1, struct timeval *time2)
 Returns the difference in milliseconds between two timeval structures.
 
static void StatsInit (ThreadPoolStats *stats)
 Initializes the statistics structure.
 
static void StatsAccountLQ (ThreadPool *tp, long diffTime)
 
static void StatsAccountMQ (ThreadPool *tp, long diffTime)
 
static void StatsAccountHQ (ThreadPool *tp, long diffTime)
 
static void CalcWaitTime (ThreadPool *tp, ThreadPriority p, ThreadPoolJob *job)
 Calculates the time the job has been waiting at the specified priority.
 
static time_t StatsTime (time_t *t)
 
static int CmpThreadPoolJob (void *jobA, void *jobB)
 Compares thread pool jobs.
 
static void FreeThreadPoolJob (ThreadPool *tp, ThreadPoolJob *tpj)
 Deallocates a dynamically allocated ThreadPoolJob.
 
static int SetPolicyType (PolicyType in)
 Sets the scheduling policy of the current process.
 
static int SetPriority (ThreadPriority priority)
 Sets the priority of the currently running thread.
 
static void BumpPriority (ThreadPool *tp)
 Determines whether any jobs need to be bumped to a higher priority Q and bumps them.
 
static void SetRelTimeout (struct timespec *time, int relMillis)
 Sets the fields of the passed in timespec to be relMillis milliseconds in the future.
 
static void SetSeed (void)
 Sets seed for random number generator. Each thread sets the seed random number generator.
 
static void * WorkerThread (void *arg)
 Implements a thread pool worker. Worker waits for a job to become available. Worker picks up persistent jobs first, high priority, med priority, then low priority.
 
static ThreadPoolJobCreateThreadPoolJob (ThreadPoolJob *job, int id, ThreadPool *tp)
 Creates a Thread Pool Job. (Dynamically allocated)
 
static int CreateWorker (ThreadPool *tp)
 Creates a worker thread, if the thread pool does not already have max threads.
 
static void AddWorker (ThreadPool *tp)
 Determines whether or not a thread should be added based on the jobsPerThread ratio. Adds a thread if appropriate.
 
int ThreadPoolInit (ThreadPool *tp, ThreadPoolAttr *attr)
 Initializes and starts ThreadPool. Must be called first and only once for ThreadPool.
 
int ThreadPoolAddPersistent (ThreadPool *tp, ThreadPoolJob *job, int *jobId)
 Adds a persistent job to the thread pool.
 
int ThreadPoolAdd (ThreadPool *tp, ThreadPoolJob *job, int *jobId)
 Adds a job to the thread pool. Job will be run as soon as possible.
 
int ThreadPoolRemove (ThreadPool *tp, int jobId, ThreadPoolJob *out)
 Removes a job from the thread pool. Can only remove jobs which are not currently running.
 
int ThreadPoolGetAttr (ThreadPool *tp, ThreadPoolAttr *out)
 Gets the current set of attributes associated with the thread pool.
 
int ThreadPoolSetAttr (ThreadPool *tp, ThreadPoolAttr *attr)
 Sets the attributes for the thread pool. Only affects future calculations.
 
int ThreadPoolShutdown (ThreadPool *tp)
 Shuts the thread pool down. Waits for all threads to finish. May block indefinitely if jobs do not exit.
 
int TPAttrInit (ThreadPoolAttr *attr)
 Initializes thread pool attributes. Sets values to defaults defined in ThreadPool.h.
 
int TPJobInit (ThreadPoolJob *job, start_routine func, void *arg)
 Initializes thread pool job. Sets the priority to default defined in ThreadPool.h. Sets the free_routine to default defined in ThreadPool.h.
 
int TPJobSetPriority (ThreadPoolJob *job, ThreadPriority priority)
 Sets the max threads for the thread pool attributes.
 
int TPJobSetFreeFunction (ThreadPoolJob *job, free_routine func)
 Sets the max threads for the thread pool attributes.
 
int TPAttrSetMaxThreads (ThreadPoolAttr *attr, int maxThreads)
 Sets the max threads for the thread pool attributes.
 
int TPAttrSetMinThreads (ThreadPoolAttr *attr, int minThreads)
 Sets the min threads for the thread pool attributes.
 
int TPAttrSetStackSize (ThreadPoolAttr *attr, size_t stackSize)
 Sets the stack size for the thread pool attributes.
 
int TPAttrSetIdleTime (ThreadPoolAttr *attr, int idleTime)
 Sets the idle time for the thread pool attributes.
 
int TPAttrSetJobsPerThread (ThreadPoolAttr *attr, int jobsPerThread)
 Sets the jobs per thread ratio.
 
int TPAttrSetStarvationTime (ThreadPoolAttr *attr, int starvationTime)
 Sets the starvation time for the thread pool attributes.
 
int TPAttrSetSchedPolicy (ThreadPoolAttr *attr, PolicyType schedPolicy)
 Sets the scheduling policy for the thread pool attributes.
 
int TPAttrSetMaxJobsTotal (ThreadPoolAttr *attr, int maxJobsTotal)
 Sets the maximum number jobs that can be qeued totally.
 
void ThreadPoolPrintStats (ThreadPoolStats *stats)
 
int ThreadPoolGetStats (ThreadPool *tp, ThreadPoolStats *stats)
 Returns various statistics about the thread pool.
 

Function Documentation

◆ AddWorker()

static void AddWorker ( ThreadPool tp)
static

Determines whether or not a thread should be added based on the jobsPerThread ratio. Adds a thread if appropriate.

Remarks
The ThreadPool object mutex must be locked prior to calling this function.
Parameters
tpA pointer to the ThreadPool object.

References THREADPOOL::attr, THREADPOOL::busyThreads, CreateWorker(), THREADPOOL::highJobQ, THREADPOOLATTR::jobsPerThread, THREADPOOL::lowJobQ, THREADPOOL::medJobQ, THREADPOOL::persistentThreads, LINKEDLIST::size, and THREADPOOL::totalThreads.

Referenced by ThreadPoolAdd().

◆ BumpPriority()

static void BumpPriority ( ThreadPool tp)
static

Determines whether any jobs need to be bumped to a higher priority Q and bumps them.

tp->mutex must be locked.

Returns
Parameters
tp.

References THREADPOOL::attr, DiffMillis(), LINKEDLIST::head, THREADPOOL::highJobQ, THREADPOOL::lowJobQ, THREADPOOLATTR::maxIdleTime, THREADPOOL::medJobQ, LINKEDLIST::size, THREADPOOLATTR::starvationTime, StatsAccountLQ(), and StatsAccountMQ().

Referenced by WorkerThread().

◆ CalcWaitTime()

static void CalcWaitTime ( ThreadPool tp,
ThreadPriority  p,
ThreadPoolJob job 
)
static

Calculates the time the job has been waiting at the specified priority.

Adds to the totalTime and totalJobs kept in the thread pool statistics structure.

Parameters
tp.
p.
job.

References DiffMillis(), StatsAccountHQ(), StatsAccountLQ(), and StatsAccountMQ().

Referenced by WorkerThread().

◆ CmpThreadPoolJob()

static int CmpThreadPoolJob ( void *  jobA,
void *  jobB 
)
static

Compares thread pool jobs.

Referenced by ThreadPoolInit().

◆ CreateThreadPoolJob()

static ThreadPoolJob * CreateThreadPoolJob ( ThreadPoolJob job,
int  id,
ThreadPool tp 
)
static

Creates a Thread Pool Job. (Dynamically allocated)

Returns
ThreadPoolJob *on success, NULL on failure.
Parameters
jobjob is copied.
idid of job.
tp.

References THREADPOOL::jobFreeList.

Referenced by ThreadPoolAdd(), and ThreadPoolAddPersistent().

◆ CreateWorker()

static int CreateWorker ( ThreadPool tp)
static

Creates a worker thread, if the thread pool does not already have max threads.

Remarks
The ThreadPool object mutex must be locked prior to calling this function.
Returns
  • 0 on success, < 0 on failure.
  • EMAXTHREADS if already max threads reached.
  • EAGAIN if system can not create thread.
Parameters
tpA pointer to the ThreadPool object.

References THREADPOOL::attr, THREADPOOLATTR::maxThreads, THREADPOOL::mutex, THREADPOOL::pendingWorkerThreadStart, THREADPOOLATTR::stackSize, THREADPOOL::start_and_shutdown, THREADPOOL::stats, THREADPOOL::totalThreads, and WorkerThread().

Referenced by AddWorker(), ThreadPoolAddPersistent(), ThreadPoolInit(), and ThreadPoolSetAttr().

◆ DiffMillis()

static long DiffMillis ( struct timeval *  time1,
struct timeval *  time2 
)
static

Returns the difference in milliseconds between two timeval structures.

Returns
The difference in milliseconds, time1-time2.
Parameters
time1.
time2.

Referenced by BumpPriority(), and CalcWaitTime().

◆ FreeThreadPoolJob()

static void FreeThreadPoolJob ( ThreadPool tp,
ThreadPoolJob tpj 
)
static

Deallocates a dynamically allocated ThreadPoolJob.

Parameters
tp.
tpjMust be allocated with CreateThreadPoolJob.

References THREADPOOL::jobFreeList.

Referenced by ThreadPoolAdd(), ThreadPoolRemove(), ThreadPoolShutdown(), and WorkerThread().

◆ SetPolicyType()

static int SetPolicyType ( PolicyType  in)
static

Sets the scheduling policy of the current process.

Returns
  • 0 on success.
  • result of GetLastError() on failure.
Parameters
in.

Referenced by ThreadPoolInit(), and ThreadPoolSetAttr().

◆ SetPriority()

static int SetPriority ( ThreadPriority  priority)
static

Sets the priority of the currently running thread.

Returns
  • 0 on success.
  • EINVAL invalid priority or the result of GerLastError.
Parameters
priority.

Referenced by WorkerThread().

◆ SetRelTimeout()

static void SetRelTimeout ( struct timespec *  time,
int  relMillis 
)
static

Sets the fields of the passed in timespec to be relMillis milliseconds in the future.

Parameters
time.
relMillismilliseconds in the future.

Referenced by WorkerThread().

◆ SetSeed()

static void SetSeed ( void  )
static

Sets seed for random number generator. Each thread sets the seed random number generator.

Referenced by WorkerThread().

◆ StatsAccountHQ()

static void StatsAccountHQ ( ThreadPool tp,
long  diffTime 
)
static
Parameters
tp.
diffTime.

References THREADPOOL::stats.

Referenced by CalcWaitTime().

◆ StatsAccountLQ()

static void StatsAccountLQ ( ThreadPool tp,
long  diffTime 
)
static
Parameters
tp.
diffTime.

References THREADPOOL::stats.

Referenced by BumpPriority(), and CalcWaitTime().

◆ StatsAccountMQ()

static void StatsAccountMQ ( ThreadPool tp,
long  diffTime 
)
static
Parameters
tp.
diffTime.

References THREADPOOL::stats.

Referenced by BumpPriority(), and CalcWaitTime().

◆ StatsInit()

static void StatsInit ( ThreadPoolStats stats)
static

Initializes the statistics structure.

Parameters
statsMust be valid non null stats structure.

Referenced by ThreadPoolInit().

◆ StatsTime()

static time_t StatsTime ( time_t *  t)
static
Parameters
t.

Referenced by ThreadPoolPrintStats(), and WorkerThread().

◆ ThreadPoolAdd()

int ThreadPoolAdd ( ThreadPool tp,
ThreadPoolJob job,
int *  jobId 
)

◆ ThreadPoolAddPersistent()

int ThreadPoolAddPersistent ( ThreadPool tp,
ThreadPoolJob job,
int *  jobId 
)

Adds a persistent job to the thread pool.

Job will be run as soon as possible. Call will block until job is scheduled.

Returns
  • 0 on success.
  • EOUTOFMEM not enough memory to add job.
  • EMAXTHREADS not enough threads to add persistent job.
Parameters
tpValid thread pool pointer.
jobValid thread pool job.
jobId.

References THREADPOOL::attr, THREADPOOL::condition, CreateThreadPoolJob(), CreateWorker(), INVALID_JOB_ID, THREADPOOL::lastJobId, THREADPOOLATTR::maxThreads, THREADPOOL::mutex, THREADPOOL::persistentJob, THREADPOOL::persistentThreads, THREADPOOL::start_and_shutdown, and THREADPOOL::totalThreads.

Referenced by StartMiniServer(), TimerThreadInit(), and TimerThreadWorker().

◆ ThreadPoolGetAttr()

int ThreadPoolGetAttr ( ThreadPool tp,
ThreadPoolAttr out 
)

Gets the current set of attributes associated with the thread pool.

Returns
  • 0 on success, nonzero on failure.
Parameters
tpvalid thread pool pointer.
outnon null pointer to store attributes.

References THREADPOOL::attr, THREADPOOL::mutex, and THREADPOOL::shutdown.

◆ ThreadPoolGetStats()

int ThreadPoolGetStats ( ThreadPool tp,
ThreadPoolStats stats 
)

Returns various statistics about the thread pool.

Only valid if STATS has been defined.

Returns
Always returns 0.
Parameters
tpValid initialized threadpool.
statsValid stats, out parameter.

References THREADPOOL::highJobQ, THREADPOOL::lowJobQ, THREADPOOL::medJobQ, THREADPOOL::mutex, THREADPOOL::persistentThreads, THREADPOOL::shutdown, THREADPOOL::stats, and THREADPOOL::totalThreads.

Referenced by PrintThreadPoolStats().

◆ ThreadPoolInit()

int ThreadPoolInit ( ThreadPool tp,
ThreadPoolAttr attr 
)

Initializes and starts ThreadPool. Must be called first and only once for ThreadPool.

Returns
  • 0 on success.
  • EAGAIN if not enough system resources to create minimum threads.
  • INVALID_POLICY if schedPolicy can't be set.
  • EMAXTHREADS if minimum threads is greater than maximum threads.
Parameters
tpMust be valid, non null, pointer to ThreadPool.
attrCan be null. if not null then attr contains the following fields:
  • minWorkerThreads - minimum number of worker threads thread pool will never have less than this number of threads.
  • maxWorkerThreads - maximum number of worker threads thread pool will never have more than this number of threads.
  • maxIdleTime - maximum time that a worker thread will spend idle. If a worker is idle longer than this time and there are more than the min number of workers running, then the worker thread exits.
  • jobsPerThread - ratio of jobs to thread to try and maintain if a job is scheduled and the number of jobs per thread is greater than this number,and if less than the maximum number of workers are running then a new thread is started to help out with efficiency.
  • schedPolicy - scheduling policy to try and set (OS dependent).

References THREADPOOL::attr, THREADPOOL::busyThreads, CmpThreadPoolJob(), THREADPOOL::condition, CreateWorker(), THREADPOOL::highJobQ, INVALID_POLICY, THREADPOOL::jobFreeList, JOBFREELISTSIZE, THREADPOOL::lastJobId, THREADPOOL::lowJobQ, THREADPOOL::medJobQ, THREADPOOLATTR::minThreads, THREADPOOL::mutex, THREADPOOL::pendingWorkerThreadStart, THREADPOOL::persistentJob, THREADPOOL::persistentThreads, THREADPOOLATTR::schedPolicy, SetPolicyType(), THREADPOOL::shutdown, THREADPOOL::start_and_shutdown, THREADPOOL::stats, StatsInit(), ThreadPoolShutdown(), THREADPOOL::totalThreads, and TPAttrInit().

Referenced by UpnpInitThreadPools().

◆ ThreadPoolPrintStats()

void ThreadPoolPrintStats ( ThreadPoolStats stats)
Parameters
stats.

References StatsTime().

◆ ThreadPoolRemove()

int ThreadPoolRemove ( ThreadPool tp,
int  jobId,
ThreadPoolJob out 
)

Removes a job from the thread pool. Can only remove jobs which are not currently running.

Returns
  • 0 on success, nonzero on failure.
  • INVALID_JOB_ID if job not found.
Parameters
tpvalid thread pool pointer.
jobIdid of job.
outspace for removed job.

References FreeThreadPoolJob(), THREADPOOL::highJobQ, INVALID_JOB_ID, THREADPOOL::lowJobQ, THREADPOOL::medJobQ, THREADPOOL::mutex, and THREADPOOL::persistentJob.

◆ ThreadPoolSetAttr()

int ThreadPoolSetAttr ( ThreadPool tp,
ThreadPoolAttr attr 
)

Sets the attributes for the thread pool. Only affects future calculations.

Returns
  • 0 on success, nonzero on failure.
  • INVALID_POLICY if policy can not be set.
Parameters
tpvalid thread pool pointer.
attrpointer to attributes, null sets attributes to default.

References THREADPOOL::attr, THREADPOOL::condition, CreateWorker(), INVALID_POLICY, THREADPOOLATTR::minThreads, THREADPOOL::mutex, THREADPOOLATTR::schedPolicy, SetPolicyType(), ThreadPoolShutdown(), THREADPOOL::totalThreads, and TPAttrInit().

◆ ThreadPoolShutdown()

int ThreadPoolShutdown ( ThreadPool tp)

Shuts the thread pool down. Waits for all threads to finish. May block indefinitely if jobs do not exit.

Returns
0 on success, nonzero on failure
Parameters
tpmust be valid tp.

References THREADPOOL::condition, FreeThreadPoolJob(), THREADPOOL::highJobQ, THREADPOOL::jobFreeList, THREADPOOL::lowJobQ, THREADPOOL::medJobQ, THREADPOOL::mutex, THREADPOOL::persistentJob, THREADPOOL::shutdown, LINKEDLIST::size, THREADPOOL::start_and_shutdown, and THREADPOOL::totalThreads.

Referenced by ThreadPoolInit(), ThreadPoolSetAttr(), and UpnpFinish().

◆ TPAttrInit()

int TPAttrInit ( ThreadPoolAttr attr)

◆ TPAttrSetIdleTime()

int TPAttrSetIdleTime ( ThreadPoolAttr attr,
int  idleTime 
)

Sets the idle time for the thread pool attributes.

Returns
Always returns 0.
Parameters
attrmust be valid thread pool attributes.
idleTime.

References THREADPOOLATTR::maxIdleTime.

Referenced by UpnpInitThreadPools().

◆ TPAttrSetJobsPerThread()

int TPAttrSetJobsPerThread ( ThreadPoolAttr attr,
int  jobsPerThread 
)

Sets the jobs per thread ratio.

Returns
Always returns 0.
Parameters
attrmust be valid thread pool attributes.
jobsPerThreadnumber of jobs per thread to maintain.

References THREADPOOLATTR::jobsPerThread.

Referenced by UpnpInitThreadPools().

◆ TPAttrSetMaxJobsTotal()

int TPAttrSetMaxJobsTotal ( ThreadPoolAttr attr,
int  maxJobsTotal 
)

Sets the maximum number jobs that can be qeued totally.

Returns
Always returns 0.
Parameters
attrmust be valid thread pool attributes.
maxJobsTotalmaximum number of jobs.

References THREADPOOLATTR::maxJobsTotal.

Referenced by UpnpInitThreadPools().

◆ TPAttrSetMaxThreads()

int TPAttrSetMaxThreads ( ThreadPoolAttr attr,
int  maxThreads 
)

Sets the max threads for the thread pool attributes.

Returns
Always returns 0.
Parameters
attrmust be valid thread pool attributes.
maxThreadsvalue to set.

References THREADPOOLATTR::maxThreads.

Referenced by UpnpInitThreadPools().

◆ TPAttrSetMinThreads()

int TPAttrSetMinThreads ( ThreadPoolAttr attr,
int  minThreads 
)

Sets the min threads for the thread pool attributes.

Returns
Always returns 0.
Parameters
attrmust be valid thread pool attributes.
minThreadsvalue to set.

References THREADPOOLATTR::minThreads.

Referenced by UpnpInitThreadPools().

◆ TPAttrSetSchedPolicy()

int TPAttrSetSchedPolicy ( ThreadPoolAttr attr,
PolicyType  schedPolicy 
)

Sets the scheduling policy for the thread pool attributes.

Returns
Always returns 0.
Parameters
attrmust be valid thread pool attributes.
schedPolicymust be a valid policy type.

References THREADPOOLATTR::schedPolicy.

◆ TPAttrSetStackSize()

int TPAttrSetStackSize ( ThreadPoolAttr attr,
size_t  stackSize 
)

Sets the stack size for the thread pool attributes.

Returns
Always returns 0.
Parameters
attrmust be valid thread pool attributes.
stackSizevalue to set.

References THREADPOOLATTR::stackSize.

Referenced by UpnpInitThreadPools().

◆ TPAttrSetStarvationTime()

int TPAttrSetStarvationTime ( ThreadPoolAttr attr,
int  starvationTime 
)

Sets the starvation time for the thread pool attributes.

Returns
Always returns 0.
Parameters
attrmust be valid thread pool attributes.
starvationTimemilliseconds.

References THREADPOOLATTR::starvationTime.

◆ TPJobInit()

int TPJobInit ( ThreadPoolJob job,
start_routine  func,
void *  arg 
)

Initializes thread pool job. Sets the priority to default defined in ThreadPool.h. Sets the free_routine to default defined in ThreadPool.h.

Returns
Always returns 0.
Parameters
jobmust be valid thread pool attributes.
funcfunction to run, must be valid.
argargument to pass to function.

References DEFAULT_FREE_ROUTINE, and DEFAULT_PRIORITY.

Referenced by readFromSSDPSocket(), ScheduleGenaAutoRenew(), SearchByTarget(), ssdp_handle_ctrlpt_msg(), ssdp_handle_device_request(), StartMiniServer(), TimerThreadInit(), UpnpGetServiceVarStatusAsync(), UpnpRenewSubscriptionAsync(), UpnpSendActionAsync(), UpnpSendActionExAsync(), UpnpSendAdvertisementLowPower(), UpnpSubscribeAsync(), and UpnpUnSubscribeAsync().

◆ TPJobSetFreeFunction()

int TPJobSetFreeFunction ( ThreadPoolJob job,
free_routine  func 
)

◆ TPJobSetPriority()

int TPJobSetPriority ( ThreadPoolJob job,
ThreadPriority  priority 
)

Sets the max threads for the thread pool attributes.

Returns
Always returns 0.
Parameters
jobmust be valid thread pool attributes.
priorityvalue to set.

Referenced by readFromSSDPSocket(), ScheduleGenaAutoRenew(), SearchByTarget(), ssdp_handle_ctrlpt_msg(), StartMiniServer(), TimerThreadInit(), UpnpGetServiceVarStatusAsync(), UpnpRenewSubscriptionAsync(), UpnpSendActionAsync(), UpnpSendActionExAsync(), UpnpSendAdvertisementLowPower(), UpnpSubscribeAsync(), and UpnpUnSubscribeAsync().

◆ WorkerThread()

static void * WorkerThread ( void *  arg)
static

Implements a thread pool worker. Worker waits for a job to become available. Worker picks up persistent jobs first, high priority, med priority, then low priority.

If worker remains idle for more than specified max, the worker is released.

Parameters
argarg -> is cast to (ThreadPool *).

References THREADPOOL::attr, BumpPriority(), THREADPOOL::busyThreads, CalcWaitTime(), THREADPOOL::condition, DEFAULT_PRIORITY, FreeThreadPoolJob(), THREADPOOL::highJobQ, THREADPOOL::lowJobQ, THREADPOOLATTR::maxIdleTime, THREADPOOLATTR::maxThreads, THREADPOOL::medJobQ, THREADPOOLATTR::minThreads, THREADPOOL::mutex, THREADPOOL::pendingWorkerThreadStart, THREADPOOL::persistentJob, THREADPOOL::persistentThreads, SetPriority(), SetRelTimeout(), SetSeed(), THREADPOOL::shutdown, LINKEDLIST::size, THREADPOOL::start_and_shutdown, THREADPOOL::stats, StatsTime(), and THREADPOOL::totalThreads.

Referenced by CreateWorker().