Thread overview | |||||
---|---|---|---|---|---|
|
December 18, 2005 Strange behaviour of threads | ||||
---|---|---|---|---|
| ||||
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 Re: Strange behaviour of threads | ||||
---|---|---|---|---|
| ||||
Posted in reply to David Ferenczi | 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 Re: Strange behaviour of threads | ||||
---|---|---|---|---|
| ||||
Posted in reply to Sean Kelly | 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
|
Copyright © 1999-2021 by the D Language Foundation