I have a non-blocking Timer class that:  counts down from whatever int the class is instantiated with each new instance of the class waits for any timer that is currently running to first finish before they start counting down  Current Design of class: class Timer{ private:    std::thread *thread;  public:   Timer(const int &amp;timer, std::mutex *mutex){     this-&gt;thread = new std::thread(         [&amp;timer, mutex](){           mutex-&gt;lock();           std::cout&lt;&lt;&quot;Counting to: &quot;&lt;&lt;timer&lt;&lt;std::endl;           for (int i=0; i &lt; timer; i++) {             std::cout&lt;&lt;i&lt;&lt;std::endl;             sleep(1);           }           std::cout&lt;&lt;&quot;Time is up&quot;&lt;&lt;std::endl;           mutex-&gt;unlock();     });   }    ~Timer(){     this-&gt;thread-&gt;join();     delete this-&gt;thread;   } };   I am calling it from main with this: int main() {   std::mutex mutex;   Timer time(3, &amp;mutex);   Timer newTime(9, &amp;mutex);   //Do something else in the meantime ...   return 0; }   Quesion: I would like to simplify the main by internalising the mutex as a static variable of the class. Something like this:  a simpler main  int main() {   Timer time(3);   Timer newTime(9);   //Do something else in the meantime ...   return 0; }   a more representative Timer class:  class Timer{ private:    std::thread *thread;   static std::mutex timerMutex;  public:   Timer(const int &amp;timer){     this-&gt;thread = new std::thread(         [&amp;timer, this](){           timerMutex.lock();           std::cout&lt;&lt;&quot;Counting to: &quot;&lt;&lt;timer&lt;&lt;std::endl;           for (int i=0; i &lt; timer; i++) {             std::cout&lt;&lt;i&lt;&lt;std::endl;             sleep(1);           }           std::cout&lt;&lt;&quot;Time is up&quot;&lt;&lt;std::endl;           timerMutex.unlock();     });   }    ~Timer(){     this-&gt;thread-&gt;join();     delete this-&gt;thread;   } };   How can I do this ?   Current Error:  error: linker command failed with exit code 1
1488
Can anyone explain why following code won't compile? At least on g++ 4.2.4.  And more interesting, why it will compile when I cast MEMBER to int?  #include &lt;vector&gt;  class Foo {   public:       static const int MEMBER = 1;   };  int main(){       vector&lt;int&gt; v;       v.push_back( Foo::MEMBER );       // undefined reference to `Foo::MEMBER'     v.push_back( (int) Foo::MEMBER ); // OK       return 0; }
47371
Let's say I have some Java code:  public class SomeClass {     static {         private final double PI = 3.14;         private final double SOME_CONSTANT = 5.76;         private final double SOME_OTHER_CONSTANT = 756.33;     }    //rest of class }   If a thread is initializing SomeClass's Class object and is in the middle of initializing the values in the static block when a second thread wants to load SomeClass's Class again, what happens to the static block?  Does the second thread ignore it assuming it's already initialized even though the first thread is not done? Or does something else happen?
72858
I am trying to learn how to specify class constructors in Java. I am starting to understand that they specify the types of instance variables of objects made from that class. They also can be used to set the instance variable initial values. The follow example is from the Java tutorial on Sun's website:  public Bicycle(int startCadence, int startSpeed, int startGear) {     gear = startGear;     cadence = startCadence;     speed = startSpeed; }   Where in your classes source code should you put the constructor(s)?  Are these arguments the names of the variables?: (int startCadence, int startSpeed, int startGear) or are gear, cadence and speed the names of the variables?  What is the difference between (int startCadence, int startSpeed, int startGear) and gear, cadence and speed?  In the unlikely event that my instructor or any administrator from Salt Lake Community College ever comes across this question, let me make my intentions clear. This question is posted in the greatest spirit of academic honesty. I ask this question to seek general advice and help in understanding the proper way to use the Java programming language. I in no way use the work of others and represent it as my own work. I use the answers provided here as a general aid in my understanding. I do all my own work and do not copy work provided by people answering my question.
38358
I've been learning C#, and I'm trying to understand lambdas.  In this sample below, it prints out 10 ten times.  class Program {     delegate void Action();     static void Main(string[] args)     {         List&lt;Action&gt; actions = new List&lt;Action&gt;();          for (int i = 0; i &lt; 10; ++i )             actions.Add(()=&gt;Console.WriteLine(i));          foreach (Action a in actions)             a();     } }   Obviously, the generated class behind the lambda is storing a reference or pointer to the int i variable, and is assigning a new value to the same reference every time the loop iterates.  Is there a way to force the lamda to grab a copy instead, like the C++0x syntax  [&amp;](){ ... } // Capture by reference   vs.  [=](){ ... } // Capture copies
574
In other words, is this Singleton implementation thread safe:  public class Singleton {     private static Singleton instance;      private Singleton() { }      static Singleton()     {         instance = new Singleton();     }      public static Singleton Instance     {         get { return instance; }     } }
120245
What's a better way to start a thread, _beginthread, _beginthreadx or CreateThread?  I'm trying to determine what are the advantages/disadvantages of _beginthread, _beginthreadex and CreateThread.  All of these functions return a thread handle to a newly created thread, I already know that CreateThread provides a little extra information when an error occurs (it can be checked by calling GetLastError)... but what are some things I should consider when I'm using these functions?  I'm working with a windows application, so cross-platform compatibility is already out of the question.  I have gone through the msdn documentation and I just can't understand, for example, why anybody would decide to use _beginthread instead of CreateThread or vice versa.  Cheers!  Update: OK, thanks for all the info, I've also read in a couple of places that I can't call WaitForSingleObject() if I used _beginthread(), but if I call _endthread() in the thread shouldn't that work? What's the deal there?
18906
I am trying to add a timed delay in a C++ program, and was wondering if anyone has any suggestions on what I can try or information I can look at?  I wish I had more details on how I am implementing this timed delay, but until I have more information on how to add a timed delay I am not sure on how I should even attempt to implement this.
52524
So I was making a class the other day and used Eclipse's method to create the equals method when I realized that it generated the following working code:  class Test {   private int privateInt;   [...]   public boolean equals(Object obj) {     [...]     Test t = (Test) obj;     if ( t.privateInt == privateInt ) {     [...]   } }   t.privateInt..???? It's suppose to be private! So I guess there is one more field visibility other than private, protected, package protected and public.  So what is happening here? How is this called? Where would somebody use this? Doesn't this break encapsulation? What if the class didn't have a mutator and I changed this? Does this happen to C++ as well? Is this an OO idiom? If not, then why did Java do it?  Generally, where can I find information about this?  Thank you.
78110
Is there any advantage of using     instead of  ?   As far as I can tell the following fragments are almost equivalent:  1. Semaphore  final Semaphore sem = new Semaphore(0); for (int i = 0; i &lt; num_threads; ++ i) {   Thread t = new Thread() {     public void run()     {       try       {         doStuff();       }       finally       {         sem.release();       }     }   };   t.start(); }  sem.acquire(num_threads);   2: CountDownLatch  final CountDownLatch latch = new CountDownLatch(num_threads); for (int i = 0; i &lt; num_threads; ++ i) {   Thread t = new Thread() {     public void run()     {       try       {         doStuff();       }       finally       {         latch.countDown();       }     }   };   t.start(); }  latch.await();   Except that in case #2 the latch cannot be reused and more importantly you need to know in advance how many threads will be created (or wait until they are all started before creating the latch.)  So in what situation might the latch be preferable?
112547
I have a class proposing translations utilities. The translations themselves should be reloaded every 30 minutes. I use Spring Timer support for that. Basically, my class looks like :  public interface Translator {     public void loadTranslations();     public String getTranslation(String key); }   loadTranslations() can be pretty long to run, so while it is running the old translations are still available. This is done by loading the translations in a local Map and just changing the reference when all translations are loaded.  My problem is : how do I make sure that when a thread is already loading translations, is a second one also tries to run, it detects that and returns immediately, without starting a second update.  A synchronized method will only queue the loads ... I'm still on Java 1.4, so no java.util.concurrent.  Thanks for your help !
42496
I have a method which should be delayed running for a specified amount of time.  Should I use  Thread thread = new Thread(() =&gt; {     Thread.Sleep(millisecond);     action(); }); thread.IsBackground = true; thread.Start();   Or  Timer timer = new Timer(o =&gt; action(), null, millisecond, -1);   I had read some  about using Thread.Sleep is bad design. But I don't really understand why.  But for using Timer, Timer has dispose method. Since the execution is delayed, I don't know how to dispose Timer. Do you have any suggestions?  Or if you have alternative codes for delayed execution are also appreciate.
11867
My singleton accessor method is usually some variant of:  static MyClass *gInstance = NULL;  + (MyClass *)instance {     @synchronized(self)     {         if (gInstance == NULL)             gInstance = [[self alloc] init];     }      return(gInstance); }   What could I be doing to improve this?
82073
Possible Duplicate:          I'd like the private member variables of a class to be accessible to a Tester class without exposing them to other classes.   In C++ I'd just declare the Tester class as a friend, how do I do this in C#? Can someone give me an example?
67839
I implemented my game-loop as described in , using the last approach with an unlimited FPS and a constant game-speed.  My problem is, that the unlimited FPS cranks up my CPU usage to nearly 100%. I understand that this is desired (as the hardware does as much as it can), but for my game, it's not really necessary (it's pretty simple). So I'd like to limit the FPS to some upper bound.  Consider my game-loop:  private static final int UPDATES_PER_SECOND = 25; private static final int WAIT_TICKS = 1000 / UPDATES_PER_SECOND; private static final int MAX_FRAMESKIP = 5;  long next_update = System.currentTimeMillis(); int frames_skipped; float interpolation;  // Start the loop: while (isRunning){     // Update game:     frames_skipped = 0;     while (System.currentTimeMillis() &gt; next_update             &amp;&amp; frames_skipped &lt; MAX_FRAMESKIP){         // Update input, move objects, do collision detection...         // Schedule next update:         next_update += WAIT_TICKS;         frames_skipped++;     }     // Calculate interpolation for smooth animation between states:     interpolation = ((float)(System.currentTimeMillis() + WAIT_TICKS - next_update)) / ((float)WAIT_TICKS);     // Render-events:     repaint(interpolation); }   How would I implement a maximum FPS?  If i implement the repaint the way I implemented the update (or use a sleep instead of "do-nothing-cycles"), then the FPS is locked, right? That is not what I want. I want the game to be able to work with lower FPS (just as it does now), but limit the FPS to a maximum of, say 250.
107586
Can a class overload methods that also exist in the publicly inherited interface? It seems like this is unambiguous and useful, but compilers (VC, Intel, GCC) all complain, at least by my construction. Below is a toy example. The inherited rebound() function has two clear overloads, yet this will not compile.  If you rename the rebound() method in either class, it works fine, but if they share the same member function name (even though they're overloaded with different argument types!) you get a fatal error of "too few arguments to function call."  The workaround is trivial (I'll just rename the methods) but I'm just trying to understand if this is a C++ restriction (and why it would be).   #include  class Bound { public:   Bound() : x0(0.0), x1(0.0) {};   Bound(double x) : x0(x), x1(x) {};   double width() const {return x1-x0;}   void rebound(const Bound *a, const Bound *b); private:   double x0, x1; };  void Bound::rebound(const Bound *a, const Bound *b) {   if (a && b) {     x0=std::min(a->x0, b->x0);     x1=std::max(a->x1, b->x1);   } }  class Node : public Bound { public:   Node(double x) : Bound(x), left(0), right(0) {};   Node(Node *a, Node *b) : left(a), right(b) {rebound();}   void rebound() { rebound(left, right); } private:   Node *left;   Node *right; };   int main() {   Node A(1.0);   Node B(2.0);   Node C(&A, &B); }
67360
Edit:    From another question I provided an answer that has links to a lot of questions/answers about singletons:   So I have read the thread  And the argument still rages.  I see Singletons as a Design Pattern (good and bad). The problem with Singleton is not the Pattern but rather the users (sorry everybody). Everybody and their father thinks they can implement one correctly (and from the many interviews I have done, most people can't). Also because everybody thinks they can implement a correct Singleton they abuse the Pattern and use it in situations that are not appropriate (replacing global variables with Singletons!).  So the main questions that need to be answered are:   When should you use a Singleton How do you implement a Singleton correctly   My hope for this article is that we can collect together in a single place (rather than having to google and search multiple sites) an authoritative source of when (and then how) to use a Singleton correctly. Also appropriate would be a list of Anti-Usages and common bad implementations explaining why they fail to work and for good implementations their weaknesses.  So get the ball rolling: I will hold my hand up and say this is what I use but probably has problems. I like "Scott Myers" handling of the subject in his books "Effective C++"     Good Situations to use Singletons (not many):         Logging frameworks   Thread recycling pools      /*  * C++ Singleton  * Limitation: Single Threaded Design  * See: http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf  *      For problems associated with locking in multi threaded applications  *  * Limitation:  * If you use this Singleton (A) within a destructor of another Singleton (B)  * This Singleton (A) must be fully constructed before the constructor of (B)  * is called.  */ class MySingleton {     private:         // Private Constructor         MySingleton();         // Stop the compiler generating methods of copy the object         MySingleton(MySingleton const&amp; copy);            // Not Implemented         MySingleton&amp; operator=(MySingleton const&amp; copy); // Not Implemented      public:         static MySingleton&amp; getInstance()         {             // The only instance             // Guaranteed to be lazy initialized             // Guaranteed that it will be destroyed correctly             static MySingleton instance;             return instance;         } };   OK. Lets get some criticism and other implementations together. :-)
6016
Why do Winforms programs have the [STAThread] attribute on the Main() method and what are the consequences of removing it?