简体   繁体   中英

How can threads synchronize their operation?

How can threads synchronize their operation? Since the threads within the same process share resources, how can the threads behave in such a way as not to interfere with other threads? Kindly explain in an easily understandable language. Thanks to all experts!

Imagine a narrow door where people can pass this door one at a time. Some times when there are too many people, they form a queue. So do correctly programmed threads - they obey to conventions like not to try to pass the door when it is occupied. Badly programmed threads, as well as bad-mannered people, can ignore the conventions and make a disorder.

The main abstraction in multithreading programming is a resource - an area of memory which can belong to at most one of a thread. Threads request for resources, wait for them, own them - and only can read or write to that memory while owing - and free them.

There are many synchronization primitives for dealing with resources, most important are semaphores, monitors, and blocking queues.

Programmers who want to design a multithreading program, should first make a plan what kind of resources will be used and how threads would exchange them. Then choose what standard synchronization facilities will be used, or design new facilities and program them. Specialized facilities usually are made with monitors.

Often teaching of multithreading programming starts with how to use monitors for thread interaction. This is wrong. First a student should master using of standard means - semaphores and blocking queues, which are sufficient for 95% of cases, and only then learn to design specialized facilities using monitors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM