Thread overview
Strange behaviour of threads
Dec 18, 2005
David Ferenczi
Dec 18, 2005
Sean Kelly
Dec 18, 2005
David Ferenczi
December 18, 2005
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?






December 18, 2005
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
December 18, 2005
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