Function thread security and Reentrant

Source: Internet
Author: User
Tags strtok
Function thread security and Reentrant
Liu aigui/aiguille. Liu

Thread-safe: If a function can be safely called by multiple threads at the same time, it is called thread-safe. The thread-safe function solves the issue of conflicting access to shared resources when multiple threads call functions.

Reentrant: A function can be used concurrently by more than one thread without worrying about data errors. The reentrant function can be interrupted at any time and run later without data loss. The reusability solves the certainty and repeatability of function running results. The code for reentrant functions is as follows:
1. Do not use static or global data inside the Function
2. No static or global data is returned. All data is provided by the function caller.
3. Use local data or make local copies of global data to protect global data.
4. If you must access global variables, use the mutex mechanism to protect global variables.
5. Do not call the reentrant function.

Relationship between the two:
1. If a function is reentrant to multiple threads, this function is thread-safe.
2. A function is thread-safe, but not necessarily reentrant.
3. reconnection is better than thread security.

For example, strtok functions are neither reentrant nor thread-safe. The strtok of the lock is not reentrant, but thread security. Strtok_r is both reentrant and thread-safe. (For details, refer to the man manual)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.