If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register or Login
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

when using multithread function - error

It is happening something that I can not understand. When I run a function which injects 100 pulses (using external electronics...) from my main program it works properly but When I do the same using a function like (thread function):
DWORD WINAPI ThreadClass::ThreadFunc(LPVOID pvParam)

It goes crazy and injects less that what I expect. I have realized that it has something to do with time...because when I write Sleep(10) for example, it works better !!

Re: when using multithread function - error

Rafraf, are you accessing the a resource (library, data, etc.) from more than one thread? If you are, then you need to guard the access of a resource with a synchronization object such as a critical section.

For example say I have a string resource that is accessed by two threads. If one thread is reading the string while the other thread is writing, there is going to be some data corruption (as the reading thread maybe getting some partially written data).

Could this be what is happening?

Btw, when you zip up your project, just zip the files up in their native format (*.h; *.cpp, etc.). That way, folks can load them up in the editor and get the benefit of getting color coded comments, formatting, etc. When saved as rtf files all this info is lost.

Re: when using multithread function - error

Rafraf, for sychronization within a process, you probably don't need to use a mutex but can use a critical section instead. I've attached a simple dialog application that uses two threads to fill and populate a list control with about 100,000 items. Items are created on one thread and pushed on to an STL vector. The second thread reads the items from the vector. Both threads lock the vector using a critical section. See the LVItemDataMgr.h for specifics.

For ease of use, the critical section is contained in the following lightweight wrapper class:

Now to be really slick, we need a class that helps us perform the locking and automatic unlocking. Note: one the most common problems with regard to multithreaded programming is forgetting to release locks when they are no longer needed. IMO, a class such as this helps prevent these sorts of problems.

This sample was originally created to illustrate a virtual listview, so there is quite a bit of UI stuff in there. However the main threading and locking code is contained within the CLVItemDataMgr.h file so it shouldn't be too hard to filter out the threading related code.