Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Help with counter  RSS feed

 
Jonny Kidd
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
Been a long time since I've posted on here, good to see the forums are as lively and helpful as ever!
OK, I will try and explain my problem (no wisecracks...!) as easily as I can.

Class Y extends Thread.
Class X creates a number of new Class Y 'threads'.

I would like a counter somewhere that all the Class Y threads can update (ie any of them can increment the counter by one).
Is it just as simple as creating a Static variable in Class X or is it not quite this simple ?

Cheers all,
Jon
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome back!

You could put the counter in class X, but since it's code in class Y that will be using it, it makes more sense to put it in Y. But either place is OK, I suppose. It doesn't actually need to be static: if a single instance of X is creating all the Ys, then that X can pass itself to Y as a constructor argument, and all the Ys can use the counter in that one X. It's actually best to avoid static variables when you can -- gives you more flexibility.

OK, now, as to whether it's that simple or not... not really. You can't just let all the threads access that single variable, or updates could be missed due to the way data can be cached locally to each thread. You have to use synchronized access methods to ensure that each thread always sees the latest data, and that no writes get lost. So minimally, you need something like this:



And then all your code needs to use these methods rather than accessing "counter" directly.

I'm going to move this to our "Threads and Synchronization" forum for further discussion.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!