螺旋锁的替代品 [英] Alternative to spinlock

查看:145
本文介绍了螺旋锁的替代品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下自旋锁方法:

I am using the following spinlock approach:

while(!hasPerformedAction()){
    //wait for the user to perform the action
    //can add timer here too
}

setHasPerformedAction(false);

return getActionPerfomed();

这基本上等待用户执行操作然后返回它。目前有些东西在继续之前请求用户回答,这就是我等到收到输入的原因。然而,我想知道这是否效率低,如果我们等待一段时间(即< = 30秒),它会减慢运行此应用程序的电脑的速度。有没有其他替代方法使用这种方法,即锁定,信号量,如果是这样的语法是什么?

this basically waits for a user to perform an action and then returns it. Currently something requests an answer from the user before continuing, this is why I wait until input is received. However I was wondering if this is inefficient and if we are waiting for a while (i.e. <= 30 secs) will it slow down the pc that is running this app. Are there any other alternatives using this approach i.e. locks, semaphores if so what is the syntax?

谢谢,

Aly

推荐答案

事实上,这不仅效率低下,甚至无法保证工作,因为没有发生 - 在你正在展示的代码中的边缘之前。创建之前发生的事情边缘您需要执行以下操作之一:

In fact, not only is this inefficient, it is not even guaranteed to work, since there is no "happens-before" edge in the code that you are showing. To create a happens-before edge you need to do one of:


  1. 访问易变变量

  2. 同步在共享资源上

  3. 使用并发工具锁。

如另一条评论所述, 最简单的解决方案,只是为了确保你的标志是一个易变的变量,并简单地在循环中抛出一个短暂的睡眠。

As mentioned in another comment, the easiest solution, is simply to ensure that your flag is a volatile variable, and simply throw a short sleep in your loop.

然而,最好的办法是在共享变量上同步/等待/通知。

However, the best thing to do would be to synchronize/wait/notify on a shared variable.

您需要阅读的方法是等待通知。有关如何使用这些内容的更好说明,请阅读本文。示例代码段如下所示;

The methods that you need to read up on are wait and notify. For a better description on how to use these, read this article. An example code snippet is shown below;

主题1

Object shared = new Object();
startThread2(shared);
synchronized (shared) {
  while (taskNotDone())
    shared.wait();
}

线程2

// shared was saved at the start of the thread
// do some stuff
markTaskAsDone();
synchronized (shared) {
  shared.notify();
}

这篇关于螺旋锁的替代品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆