简体   繁体   English

线程如何同步它们的操作?

[英]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.学生首先要掌握标准手段的使用——信号量和阻塞队列,这些都足以应付95%的情况,然后才学会使用监视器设计专门的设施。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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