www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Strange behaviour of threads

reply David Ferenczi <raggae ferenczi.net> writes:
I'm experimenting with threads and I encountered some strange behaviour. If
the code below is executed the result is:

first
second
first
first
first
first
first
...

If I comment out the call to din.readLine() everything seems to be correct:

first
second
first
second
first
second
first
second
first
second
first
second
...


private import std.thread;
private import std.cstream;
private import std.c.time;

int main(char[][] args)
{
    MyClass myObj = new MyClass();
    return myObj.run();
}

class MyClass
{
public:
    this () {}

    int run ()
    {
        myThread_ = new Thread(&threadFunction);
        myThread_.start();
        
        while (true)
        {
            dout.writeLine("first");
            sleep(1);
        }
    }

private:
    Thread myThread_;

    int threadFunction()
    {
        while (true)
        {
            dout.writeLine("second");
            char[] line = din.readLine();
            sleep(1);
        }

        return 0;
    }
}


Could anyone please explain me, why do I get differrent behaviour?
Dec 18 2005
parent reply Sean Kelly <sean f4.ca> writes:
David Ferenczi wrote:
 I'm experimenting with threads and I encountered some strange behaviour. If
 the code below is executed the result is:
 
 first
 second
 first
 first
 first
 first
 first
 ...
 
 If I comment out the call to din.readLine() everything seems to be correct:
 
 first
 second
 first
 second
 first
 second
 first
 second
 first
 second
 first
 second
 ...
 
 
 private import std.thread;
 private import std.cstream;
 private import std.c.time;
 
 int main(char[][] args)
 {
     MyClass myObj = new MyClass();
     return myObj.run();
 }
 
 class MyClass
 {
 public:
     this () {}
 
     int run ()
     {
         myThread_ = new Thread(&threadFunction);
         myThread_.start();
         
         while (true)
         {
             dout.writeLine("first");
             sleep(1);
         }
     }
 
 private:
     Thread myThread_;
 
     int threadFunction()
     {
         while (true)
         {
             dout.writeLine("second");
             char[] line = din.readLine();
             sleep(1);
         }
 
         return 0;
     }
 }
 
 
 Could anyone please explain me, why do I get differrent behaviour?
I think the initial call to din.readLine is waiting for input from the console, so writeLine("first") just runs continuously. Sean
Dec 18 2005
parent David Ferenczi <raggae ferenczi.net> writes:
Sean Kelly wrote:
 I think the initial call to din.readLine is waiting for input from the
 console, so writeLine("first") just runs continuously.
 
 
 Sean
Thank you very much, this was the problem! I feel stupid that I didn't think of that this function call may have been blocking. Thanks, again, David
Dec 18 2005