Computer Chess Club Archives


Search

Terms

Messages

Subject: Re: Threads

Author: James Robertson

Date: 22:29:30 04/06/99

Go up one level in this thread


On April 07, 1999 at 01:04:51, Bruce Moreland wrote:

>
>On April 06, 1999 at 21:30:34, James Robertson wrote:
>
>>I am thinking of making my program multithreaded to ease implementation of
>>several things. But before I begin, I have several questions: first, if I have
>>an input thread that just sits with cin, and my search thread is doing stuff in
>>the background, will the search thread be slowed? Second, about locking and
>>unlocking resources shared between threads; how is this usually done? If I just
>>declare a variable, say
>
>If you have two threads and one of them is blocked like this, it isn't taking
>any CPU time.
>
>>bool locked = false;
>>
>>Can I "lock" and "unlock" resources by just:
>>
>>....
>>
>>//see if the variable is locked
>>if (!locked) {
>>  locked = true;
>>  //change shared resources
>>  locked = false;
>>}
>>
>>Will this work?
>
>This would be an excellent way to set your head on fire.

I see; thread 1 could have just discovered that the locked = false, and then
before it can set locked to true, thread 2 comes in and sees that it is also
false?

>
>Imagine if two things are contending for a resource, they both hit the !locked
>thing at the same time, pass this test, then set "locked" to true, so you have
>two of them in the same region at the same time.  You can't make any assumptions
>when you do multi-threaded code, the other thread could be doing anything at any
>time, and could take an arbitrarily long or short time until it's done doing it.
>
>Since you said "thread" instead of "task" I assume you are using the Win32 API.

Yes.

>In the documentation for MSVC (assuming you are using that), there is some basic
>stuff about multithreading that you should read.

Ok.

>
>If you just want to do what you said above, you can use a CRITICAL_SECTION,
>which will implement the atomic test-and-set operation that you were trying to
>do above (it does everything you did in your example, but it can't kill itself
>the way I described, since the "test" and the "set" are guaranteed to happen in
>such a way that nothing can slip between them).

Just out of curiosity, how does a critical_section do this? Is it something
built into Windows?

James

>
>If you are serious about this, buy yourself some Tylenol, you'll need it for
>debugging, since multithreading adds a whole new dimension in bugs.
>
>bruce



This page took 0.01 seconds to execute

Last modified: Thu, 15 Apr 21 08:11:13 -0700

Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.