473,394 Members | 1,642 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Threading problem.

Hi All,

I'm having a bit of problem with threading, when I first call Start() on my
code the thread work, I call Stop() and it stopped, but when I call Start()
again my thread is not started. Although in the debugger I can see that it
went to the Start() method and creating the thread again.

Can anyone help me? This is the code:

<snip>

public static MySingleton GetInstance() {
if (instance == null) {
instance = new MySingleton();
}
return instance;
}

public void Start() {
lock (this) {
if (!started){
started = true;
thread = new Thread(new ThreadStart(Run));
thread.Start();
}
}
}

public void Stop() {
stopped = true;
}

private void Run() {
while (!stopped) {
Console.WriteLine("Running ...");
Thread.Sleep(1000);
}
thread.Join();
started = false;
}

</snip>
Thanks,

/m
Nov 15 '05 #1
10 1371
Try thread.Abort() on the Stop method

Hope this helps
Dan Cimpoiesu

"muscha" <mu****@no.spam.net> wrote in message
news:eh*************@tk2msftngp13.phx.gbl...
Hi All,

I'm having a bit of problem with threading, when I first call Start() on my code the thread work, I call Stop() and it stopped, but when I call Start() again my thread is not started. Although in the debugger I can see that it
went to the Start() method and creating the thread again.

Can anyone help me? This is the code:

<snip>

public static MySingleton GetInstance() {
if (instance == null) {
instance = new MySingleton();
}
return instance;
}

public void Start() {
lock (this) {
if (!started){
started = true;
thread = new Thread(new ThreadStart(Run));
thread.Start();
}
}
}

public void Stop() {
stopped = true;
}

private void Run() {
while (!stopped) {
Console.WriteLine("Running ...");
Thread.Sleep(1000);
}
thread.Join();
started = false;
}

</snip>
Thanks,

/m

Nov 15 '05 #2
muscha <mu****@no.spam.net> wrote:
I'm having a bit of problem with threading, when I first call Start() on my
code the thread work, I call Stop() and it stopped, but when I call Start()
again my thread is not started. Although in the debugger I can see that it
went to the Start() method and creating the thread again.


Your code is slightly odd - I don't see why you're trying to call
thread.Join() within Run, when the thread it's running in should be the
thread it's trying to join anyway!

Note also that your singleton implementation isn't threadsafe - see
http://www.pobox.com/~skeet/csharp/singleton.html

Finally, the way you're testing the "stopped" flag is dodgy - because
you haven't got any synchronization there, there's no guarantee that
other threads will see new values.

If you could post a short but *complete* example which demonstrates the
problem, that would help.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #3
Change the 2 methods below and it should work:

public void Stop()
{
lock (this)
{
stopped = true;
thread.Join();
started = false;
stopped = false;
}
}

private void Run()
{
while (!stopped)
{
Console.WriteLine("Running ...");
Thread.Sleep(1000);
}
}

José
"muscha" <mu****@no.spam.net> wrote in message
news:eh*************@tk2msftngp13.phx.gbl...
Hi All,

I'm having a bit of problem with threading, when I first call Start() on my code the thread work, I call Stop() and it stopped, but when I call Start() again my thread is not started. Although in the debugger I can see that it
went to the Start() method and creating the thread again.

Can anyone help me? This is the code:

<snip>

public static MySingleton GetInstance() {
if (instance == null) {
instance = new MySingleton();
}
return instance;
}

public void Start() {
lock (this) {
if (!started){
started = true;
thread = new Thread(new ThreadStart(Run));
thread.Start();
}
}
}

public void Stop() {
stopped = true;
}

private void Run() {
while (!stopped) {
Console.WriteLine("Running ...");
Thread.Sleep(1000);
}
thread.Join();
started = false;
}

</snip>
Thanks,

/m

Nov 15 '05 #4
Jon and all,
Note also that your singleton implementation isn't threadsafe - see
http://www.pobox.com/~skeet/csharp/singleton.html
Thanks for that.
If you could post a short but *complete* example which demonstrates the
problem, that would help.


Here is my class, I followed people's suggestion and it seems working now,
however is it thread safe?
using System;
using System.Threading;

namespace Scheduler
{
public class MySingleton
{
private static MySingleton instance;
private static Object padlock = new Object();
private Thread thread;
private bool stopped = false;
private bool started = false;

/// <summary>
/// Private constructor so this thread can't be instantiated.
/// </summary>
private MySingleton()
{
}

~MySingleton()
{
Stop();
}

public static MySingletonGetInstance()
{
if (instance == null)
{
lock (padlock)
{
if (instance == null)
{
instance = new MySingleton();
}
}
}
return instance;
}

public void Start()
{
lock (this)
{
if (!started)
{
started = true;
thread = new Thread(new ThreadStart(this.Run));
thread.Start();
}
}
}

public void Stop()
{
lock (this)
{
stopped = true;
thread.Join();
started = false;
stopped = false;
}
}

private void Run()
{
while (!stopped)
{
Console.WriteLine("Running ...");
Thread.Sleep(1000);
}
}
}
}

Thanks,

/m
Nov 15 '05 #5
Jon and all,
Note also that your singleton implementation isn't threadsafe - see
http://www.pobox.com/~skeet/csharp/singleton.html
Thanks for that.
If you could post a short but *complete* example which demonstrates the
problem, that would help.


Here is my class, I followed people's suggestion and it seems working now,
however is it thread safe?
using System;
using System.Threading;

namespace Scheduler
{
public class MySingleton
{
private static MySingleton instance;
private static Object padlock = new Object();
private Thread thread;
private bool stopped = false;
private bool started = false;

/// <summary>
/// Private constructor so this thread can't be instantiated.
/// </summary>
private MySingleton()
{
}

~MySingleton()
{
Stop();
}

public static MySingletonGetInstance()
{
if (instance == null)
{
lock (padlock)
{
if (instance == null)
{
instance = new MySingleton();
}
}
}
return instance;
}

public void Start()
{
lock (this)
{
if (!started)
{
started = true;
thread = new Thread(new ThreadStart(this.Run));
thread.Start();
}
}
}

public void Stop()
{
lock (this)
{
stopped = true;
thread.Join();
started = false;
stopped = false;
}
}

private void Run()
{
while (!stopped)
{
Console.WriteLine("Running ...");
Thread.Sleep(1000);
}
}
}
}

Thanks,

/m
Nov 15 '05 #6
Hi Muscha,

Looks to be thread safe after a quick glance anyway. It it were my code I
would first check that the thread is running in Stop to guard against the
possibility that Start was never called.

Cheers

Doug Forster

"muscha" <mu****@no.spam.net> wrote in message
news:uo*************@TK2MSFTNGP11.phx.gbl...
Jon and all,
Note also that your singleton implementation isn't threadsafe - see
http://www.pobox.com/~skeet/csharp/singleton.html


Thanks for that.
If you could post a short but *complete* example which demonstrates the
problem, that would help.


Here is my class, I followed people's suggestion and it seems working now,
however is it thread safe?
using System;
using System.Threading;

namespace Scheduler
{
public class MySingleton
{
private static MySingleton instance;
private static Object padlock = new Object();
private Thread thread;
private bool stopped = false;
private bool started = false;

/// <summary>
/// Private constructor so this thread can't be instantiated.
/// </summary>
private MySingleton()
{
}

~MySingleton()
{
Stop();
}

public static MySingletonGetInstance()
{
if (instance == null)
{
lock (padlock)
{
if (instance == null)
{
instance = new MySingleton();
}
}
}
return instance;
}

public void Start()
{
lock (this)
{
if (!started)
{
started = true;
thread = new Thread(new ThreadStart(this.Run));
thread.Start();
}
}
}

public void Stop()
{
lock (this)
{
stopped = true;
thread.Join();
started = false;
stopped = false;
}
}

private void Run()
{
while (!stopped)
{
Console.WriteLine("Running ...");
Thread.Sleep(1000);
}
}
}
}

Thanks,

/m

Nov 15 '05 #7
muscha <mu****@no.spam.net> wrote:
Jon and all,
Note also that your singleton implementation isn't threadsafe - see
http://www.pobox.com/~skeet/csharp/singleton.html


Thanks for that.


I note that you're using the double-checked locking algorithm though,
which I don't believe to be thread-safe.
If you could post a short but *complete* example which demonstrates the
problem, that would help.


Here is my class, I followed people's suggestion and it seems working now,
however is it thread safe?


Not quite. Aside from the singleton problem, you're not locking on
anything before checking the stopped flag in Run. I would also suggest
not locking on "this" but locking on another reference private to the
class (just create a new object, like padlock but with an instance
variable).

I'm also not keen on the finalizer - do you think you really need it,
particularly? It's only going to be invoked when the AppDomain is
unloaded, and then only "some time after that". I would personaly just
get rid of it.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #8
> > Here is my class, I followed people's suggestion and it seems working
now,
however is it thread safe?


Not quite. Aside from the singleton problem, you're not locking on
anything before checking the stopped flag in Run. I would also suggest
not locking on "this" but locking on another reference private to the
class (just create a new object, like padlock but with an instance
variable).


What's the difference from locking a separate object to lock than doing lock
on this? Isn't that by doing lock(this) in the beginning of the method, you
practically synchronize the entire method call?

thanks,

/m


Nov 15 '05 #9
muscha <mu****@no.spam.net> wrote:
Not quite. Aside from the singleton problem, you're not locking on
anything before checking the stopped flag in Run. I would also suggest
not locking on "this" but locking on another reference private to the
class (just create a new object, like padlock but with an instance
variable).


What's the difference from locking a separate object to lock than doing lock
on this? Isn't that by doing lock(this) in the beginning of the method, you
practically synchronize the entire method call?


If you lock on this, then something else might also lock on it, and you
could end up with a deadlock. If you lock on a reference that only your
instance will ever know about, you have more control.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #10
"Doug Forster" <doug_ZAPTHIS_AT_TONIQ_ZAPTHIS_co.nz> wrote:
Looks to be thread safe after a quick glance anyway.
And that's why you should never trust multithreading code to quick
glances :)
It it were my code I
would first check that the thread is running in Stop to guard against the
possibility that Start was never called.


That would indeed be a good thing to do - I missed that.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

65
by: Anthony_Barker | last post by:
I have been reading a book about the evolution of the Basic programming language. The author states that Basic - particularly Microsoft's version is full of compromises which crept in along the...
19
by: Jane Austine | last post by:
As far as I know python's threading module models after Java's. However, I can't find something equivalent to Java's interrupt and isInterrupted methods, along with InterruptedException....
17
by: Andrae Muys | last post by:
Found myself needing serialised access to a shared generator from multiple threads. Came up with the following def serialise(gen): lock = threading.Lock() while 1: lock.acquire() try: next...
2
by: Egor Bolonev | last post by:
hi all my program terminates with error i dont know why it tells 'TypeError: run() takes exactly 1 argument (10 given)' =program==================== import os, os.path, threading, sys def...
77
by: Jon Skeet [C# MVP] | last post by:
Please excuse the cross-post - I'm pretty sure I've had interest in the article on all the groups this is posted to. I've finally managed to finish my article on multi-threading - at least for...
11
by: Paul Sijben | last post by:
I am stumped by the following problem. I have a large multi-threaded server accepting communications on one UDP port (chosen for its supposed speed). I have been profiling the code and found...
17
by: OlafMeding | last post by:
Below are 2 files that isolate the problem. Note, both programs hang (stop responding) with hyper-threading turned on (a BIOS setting), but work as expected with hyper-threading turned off. ...
9
by: cgwalters | last post by:
Hi, I've recently been working on an application which does quite a bit of searching through large data structures and string matching, and I was thinking that it would help to put some of this...
5
by: CCLeasing | last post by:
For an application I'm creating I want to create a 'fake' progress bar. By fake I mean a progress bar that looks like it's doing something but actually isn't. I know philosophically this isn't...
126
by: Dann Corbit | last post by:
Rather than create a new way of doing things: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2497.html why not just pick up ACE into the existing standard:...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.