Skip to content

Thread id (is a simple unsigned long)

pthread_t thread;

Create a new thread

This block starts a new thread and calls the function subThread from within the new thread with a void pointer to threadParams. The calling thread resumes executing in the original thread.

pthread_create(&thread, // pointer to thread descriptor
    (void *)0, // use default attributes
    subThread, // thread function entry point
    (void *)&(threadParams) // parameters to pass in
);

Terminate a thread

This function terminates calling thread. This function never returns because the thread does not exist anymore.

void pthread_exit(void *retval);

https://linux.die.net/man/3/pthread_exit

Wait for a thread

Wait for specific thread to terminate. The *retval used in pthread_exit will be copied to the **retval.

int pthread_join(pthread_t thread, void **retval);

https://linux.die.net/man/3/pthread_join

Misc functions

Get the id of the calling thread

pthread_t pthread_self(void);

https://linux.die.net/man/3/pthread_self

Linux scheduling types

https://man7.org/linux/man-pages/man7/sched.7.html

Manipulate runtime attributes of a process with chrt

SCHED_FIFO

Simple scheduling without time slicing or preemption. Thread gets the highest priority but are executed at a first in first out order. Time slicing is disabled. This can lock up a CPU when a thread is in a infinite loop.

Output of the simplethread-affinity-fifo example, threads are executed in order.

Thread idx=0, sum[0...0]=0, running on CPU=3, start=1788203792.635252, stop=1788203792.821751
Thread idx=1, sum[0...1]=1, running on CPU=3, start=1788203792.636947, stop=1788203792.828664
Thread idx=2, sum[0...2]=3, running on CPU=3, start=1788203792.638927, stop=1788203793.102232
Thread idx=3, sum[0...3]=6, running on CPU=3, start=1788203792.639963, stop=1788203793.108654
Thread idx=5, sum[0...5]=15, running on CPU=3, start=1788203792.643856, stop=1788203793.388333
Thread idx=4, sum[0...4]=10, running on CPU=3, start=1788203792.641964, stop=1788203793.389065
Thread idx=6, sum[0...6]=21, running on CPU=3, start=1788203792.644933, stop=1788203793.666424
Thread idx=8, sum[0...8]=36, running on CPU=3, start=1788203792.648938, stop=1788203793.974692

SCHED_RR

Enhancement of SCHED_FIFO but with a maximum time quantum.

SCHED_OTHER

The default Linux scheduler. With time slicing.