java本机方法调用是原子调用吗?
我需要某些操作才能成为原子操作。
这里“原子”的意思是“一旦该方法开始执行,它不应该被中断直到它完成,并且即使线程调度程序也不应该在该线程处于运行状态时使该线程进入可运行状态”。
所有方法都是 Native 方法,并且多个线程并发运行来执行这些方法。
第一个问题:本机方法执行本质上是原子的吗?
第二个问题:为了实现原子性,我们可以使用java并发/锁API吗?如果可以,请提供任何示例/链接(如果可能)?
谢谢。
I need certain operation to be Atomic.
Here 'Atomic' means to say "once that method started execution, it shouldn't be interrupted till it finishes, And even thread scheduler also should not make that thread to Runnable state once its in Running state".
All methods are Native methods and multiple threads are running concurrently to execute these methods.
First Question: Is the native methods execution is Atomic in nature?
Second Question : To achieve the Atomicity, Can we use java concurent/lock APIs, if yes, please provide any example/link if possible?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果我对这个问题的理解是正确的,那么您是在问:我是否可以实现某个线程始终在 CPU 上运行直到完成?需要明确的是,在此期间它不应该被另一个线程替换。
答案是:即使是(我认为不是),这也与原子性无关。因为如果您有多个 CPU,多个线程仍然可以访问和更改相同的数据,同时所有线程都真正不间断地运行。因此,即使您定义了“原子性”,您仍然会遇到并发问题。
如果您只想要传统意义上的线程安全,那么是的,您可以使用 java-locks 等来实现这一点,即使您调用本机方法。请参阅 http://journals.ecs.soton。 ac.uk/java/tutorial/native1.1/implementing/sync.html 查看本机方法内的 java 线程同步示例。
If i understand the question right, you are asking for: Is it possible for me to achieve that a certain thread will always be running on the CPU until it is finished? To be clear, it should not be replaced by another thread during that time.
The answer is: Even if it was (and i don't think it is), this would have nothing to do with atomicity. Because if you have multiple CPU's, multiple Threads can still access and change the same data while all are truely running uninterrupted at the same time. Therefore, even with your definition of "atomicity", you would still end-up with concurrency problems.
If you just want thread-safety in the conventional sense, then yes, you can use java-locks etc. to achieve that, even if you call native methods. see http://journals.ecs.soton.ac.uk/java/tutorial/native1.1/implementing/sync.html for an example of java thread synchronization from within native methods.
为了防止中断,您必须使用机器代码指令 cli 和 sti 来禁用和启用中断(在 x86/x64 上)。这甚至不是你可以用简单的 C 语言完成的事情。
这是非常低水平的,因为很少有人这样做。主要是因为它很少有用。主要关注的通常是与其他线程交互的行为,这就是为什么大多数用例都以这种方式定义原子,而不是中断方面的原子。
To prevent an interrupt you must the the machine code instructions cli and sti to disable and enable interrupts (on x86/x64). It not something you can even do in plain C language.
This is so low level as it is rarely done. Largely because its rarely very useful. The main concern is usually the behaviour of interaction with other threads which is why Atomic is defined this way for most use cases, not atomic in terms of interrupts.
您对原子的定义是非标准的。这是一个更加标准定义。
Your definition of atomic is non-standard. This is a more standard definition.