Книга: Programming with POSIX® Threads
6.5 Thread-safe functions
Although ANSI C and POSIX 1003.1-1990 were not developed with threads in mind, most of the functions they define can be made thread-safe without changing the external interface. For example, although malloc and free must be changed to support threads, code calling these functions need not be aware of the changes. When you call malloc, it locks a mutex (or perhaps several mutexes) to perform the operation, or may use other equivalent synchronization mechanisms. But your code just calls malloc as it always has, and it does the same thing as always.
In two main classes of functions, this is not true:
• Functions that traditionally return pointers to internal static buffers, for example, asctime. An internal mutex wouldn't help, since the caller will read the formatted time string some time after the function returns and, therefore, after the mutex has been unlocked.
• Functions that require static context between a series of calls, for example, strtok, which stores the current position within the token string in a local static variable. Again, using a mutex within strtok wouldn't help, because other threads would be able to overwrite the current location between two calls.
In these cases, Pthreads has defined variants of the existing functions that are thread-safe, which are designated by the suffix "_r" at the end of the function name. These variants move context outside the library, under the caller's control. When each thread uses a private buffer or context, the functions are thread-safe. You can also share context between threads if you want — but the caller must provide synchronization between the threads. If you want two threads to search a directory in parallel, you must synchronize their use of the shared struct dirent passed to readdir_r.
A few existing functions, such as ctermid, are already thread-safe as long as certain restrictions are placed on parameters. These restrictions are noted in the following sections.
- 1.2.5 Thread safety and reentrancy
- 7.3.1 Modifying libraries to be thread-safe
- 9.3.11 Thread-safe functions
- 6 POSIX adjusts to threads
- 6.6.5 SIGEV_THREAD
- CHAPTER 4 Functions and Libraries in mikroC
- 4 A few ways to use threads
- Функция pthread_rwlock_trywrlock
- Functions
- Basic Functions
- Using Functions in Shell Scripts
- 5.5. The init Thread