简体   繁体   中英

Give a C++ class foo, inside, it has a synchronized method. How to guarantee the synchronized method being accessed by only one thread

Give a C++ class foo, inside, it has a synchronized method. We have two objects of foo, called, f1 and f2, if f1 and f2 are concurrently running, can we guarantee the synchronized method being accessed by only one thread?

My idea:

Use a mutex, whoever needs to access the method, who get the mutex.

This interview question seems not to be so simple.

Any solutions ?

thanks

In java, unless the method is static, you need to synchronize externally in order to ensure the method is only called by one thread at one time.

You can also synchronize the method itself on a static variable of the class. Eg

public class myClass
{
  private static Object myLock = new Object();

  public void myMethod()
  {
    synchronized(myLock)
    {
      // ...
    }
  }
}

With a static method you'd do the following in Java:

class Foo {

   public static synchronized void mymethod() {
      ...
   }
}

You actually synchronize on Foo.class in this case.

If you have an instance method (ie non-static) and you need to synchronize, you could put a synchronized block into the method and synchronize on any object even on the class itself:

public void mymethod() {
  synchronized( Foo.class ) {
    ...
  }
}

Note that this would synchronize access to other static synchronized methods in the same class du to the shared lock object Foo.class .

Btw, the answer to that question depends on the definition of accessed : Multiple threads can access the method by trying to invoke it, read its reflection metadata or even enter it in case of nested synchronized blocks but they would normally not execute it concurrently unless parts of the method are not synchronized (or synchronized on a different lock object).

如果我理解正确并且您希望它在所有实例中同步,则使该方法静态同步

If you have two different instances of class foo , then it does not matter what happens because each has a different copy of the method and the synchronization happens on the this object:

public synchronized void method() {
    // code
}

is equivalent to:

public void method() {
   synchronized(this) {
      // code
   }
}

Having said this, if each thread calls method from a different instance of foo :

  1. they will acquire different locks
  2. they will not produce any data race if you are not modifying data outside of class foo

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