Ch 12 Thread Control

Ch 12 Thread Control

Thread Limits

Thread limits can be queried using the sysconf function. Taking Linux systems as an example:

  • Maximum number of times operating system implementations can destroy thread-specific data when a thread exits: 4
  • Maximum number of thread keys that a process can create: 1024
  • Minimum number of bytes for a thread stack: 16384, approximately 16K
  • Maximum number of threads that a process can create: no definite limit

Thread States

Joinable and Detached

  • Default state is joinable: meaning it can be reclaimed or terminated by other threads
  • Detached: its resources cannot be reclaimed or killed by other threads; only when the thread ends can the system reclaim them

Reentrancy

If a function can be safely called by multiple threads at the same time point, then this function is considered thread-safe, indicating it is reentrant.

Thread-Specific Data

errno is a typical example of thread-specific data. Keys need to be used to access thread-specific data.

Threads and Fork

When threads call fork, it creates a copy of the address space for the child process and inherits the state of each mutex, read-write lock, and condition variable from the parent process. If exec is not immediately called afterward, the lock states need to be cleaned up. Therefore, when using fork, you need to call pthread_atfork.

Threads and I/O

Consider two threads simultaneously reading the same file, sharing the same file descriptor. They first use lseek to position, then read to read. In a multi-threaded environment, inconsistency issues may arise. Therefore, using pread and pwrite allows threads to perform atomic read/write operations, solving the problem of concurrent threads performing read/write operations on the same file.