Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.clipper.visual-objects > #5369 > unrolled thread

Thread safe code - any caveats?

Started byMartin <spam@spam.spam>
First post2013-06-18 11:36 +0100
Last post2013-06-19 17:04 +0100
Articles 20 — 4 participants

Back to article view | Back to comp.lang.clipper.visual-objects


Contents

  Thread safe code - any caveats? Martin <spam@spam.spam> - 2013-06-18 11:36 +0100
    Re: Thread safe code - any caveats? "Ginny Caughey" <gcaughey@online.hotmail.com> - 2013-06-18 06:59 -0400
      Re: Thread safe code - any caveats? Martin <spam@spam.spam> - 2013-06-18 12:05 +0100
        Re: Thread safe code - any caveats? "Ginny Caughey" <gcaughey@online.hotmail.com> - 2013-06-18 12:41 -0400
          Re: Thread safe code - any caveats? Martin <spam@spam.spam> - 2013-06-19 09:14 +0100
            Re: Thread safe code - any caveats? "Ginny Caughey" <gcaughey@online.hotmail.com> - 2013-06-19 07:24 -0400
              Re: Thread safe code - any caveats? Martin <spam@spam.spam> - 2013-06-19 12:40 +0100
                Re: Thread safe code - any caveats? "Ginny Caughey" <gcaughey@online.hotmail.com> - 2013-06-19 10:02 -0400
                  Re: Thread safe code - any caveats? Martin <spam@spam.spam> - 2013-06-19 17:07 +0100
                    Re: Thread safe code - any caveats? "Ginny Caughey" <gcaughey@online.hotmail.com> - 2013-06-20 07:22 -0400
                      Re: Thread safe code - any caveats? Martin <spam@spam.spam> - 2013-06-20 17:12 +0100
                        Re: Thread safe code - any caveats? "Ginny Caughey" <gcaughey@online.hotmail.com> - 2013-06-20 14:04 -0400
                          Re: Thread safe code - any caveats? "Martin \(BT\)" <martin-spam@btinternet.com> - 2013-06-20 20:27 +0100
                            Re: Thread safe code - any caveats? "Ginny Caughey" <gcaughey@online.hotmail.com> - 2013-06-21 06:54 -0400
                              Re: Thread safe code - any caveats? Martin <spam@spam.spam> - 2013-06-21 15:39 +0100
                                Re: Thread safe code - any caveats? Martin <spam@spam.spam> - 2013-06-21 15:54 +0100
                                  Re: Thread safe code - any caveats? "Ginny Caughey" <gcaughey@online.hotmail.com> - 2013-06-21 12:12 -0400
                                    Re: Thread safe code - any caveats? Martin <spam@spam.spam> - 2013-06-21 17:15 +0100
                Re: Thread safe code - any caveats? dlzc <dlzc1@cox.net> - 2013-06-19 08:04 -0700
                  Re: Thread safe code - any caveats? Martin <spam@spam.spam> - 2013-06-19 17:04 +0100

#5369 — Thread safe code - any caveats?

FromMartin <spam@spam.spam>
Date2013-06-18 11:36 +0100
SubjectThread safe code - any caveats?
Message-ID<WKWvt.136194$I84.63382@fx07.fr7>
Got quite a bit on the go now, but need a thread with data access, also 
it may need to run continually.

Anything I need to be careful with please?

Tahnks

Martin

[toc] | [next] | [standalone]


#5370

From"Ginny Caughey" <gcaughey@online.hotmail.com>
Date2013-06-18 06:59 -0400
Message-ID<51c03d5a$0$59644$c3e8da3$66d3cc2f@news.astraweb.com>
In reply to#5369
If you access DBF files, don't share the workarea with any other thread. Use 
normal multiuser access patterns.
No dynamic data types such as strings that might trigger garbage collection.
Seriously consider why this needs to be a separate thread instead of a 
separate app.

HTH,
Ginny

"Martin"  wrote in message news:WKWvt.136194$I84.63382@fx07.fr7...

Got quite a bit on the go now, but need a thread with data access, also
it may need to run continually.

Anything I need to be careful with please?

Tahnks

Martin 

[toc] | [prev] | [next] | [standalone]


#5371

FromMartin <spam@spam.spam>
Date2013-06-18 12:05 +0100
Message-ID<M9Xvt.159290$xf1.107935@fx16.fr7>
In reply to#5370
Thanks Ginny

The main reason is neatness of code and communications.

I will be sending the rack number in a PSZ in a struct but will need to 
search a DBF for it.

This is the code I am converting, this is in XBase++, but need it in VO 
2.8. AS you can see it is not especially long, and is stable, but I 
can't link in huge amounts of VO into Xbase++

	cBat	:= Left(cRack,10)
//	Now we could monitor order or rack	
	IF TDelList->(DBSeek(cRack))
		TBarCode->(OrdSetFocus(2))
		TBarList->(OrdSetFocus(2))

//		Check the order
		cOrder	:= TDelList->DEL_Order
		IF TOrder->(DBSeek(cOrder))
			cCust	:= Torder->OD_CustNo
		ELSE
			cCust	:= 'xxxxxxxxxx'
		ENDIF

		lOk	:= .T.
		DO WHILE TDellist->DEL_Key == cBat .AND. !TDellist->(EoF())
			cOrder	:= TDelList->DEL_Order
			IF TOrder->(DBSeek(cOrder))
				IF cCust <> Torder->OD_CustNo
					EXIT
				ENDIF

//				Check the barcodes
				TBarCode->(DBSeek(cOrder))
				DO WHILE TBarCode->BC_Order == cOrder .AND. !TBarCode->(EoF())
					cBarcode	:= TBarCode->BC_Key

					IF !TBarList->(DBSeek(cProc+cBarcode))
						lOk	:= .F.
						EXIT
					ENDIF
					
					IF TBarList->PL_Qty <= 0
						lOk	:= .F.
						EXIT
					ENDIF
					
					TBarCode->(DBSkip(1))
				ENDDO
			ENDIF
			TDelList->(DBSkip(1))
		ENDDO

		IF lOk
//			Fully loaded!!!!
//			Hit_Key('fully loaded')

			nPos := AT(cErr,'OPQRSTUVWXYZ')
			SBeep(nPos,9,'WAV')
		ENDIF
		
		TBarCode->(OrdSetFocus(1))
		TBarList->(OrdSetFocus(1))
	ENDIF	





On 18/06/2013 11:59, Ginny Caughey wrote:
> If you access DBF files, don't share the workarea with any other thread.
> Use normal multiuser access patterns.
> No dynamic data types such as strings that might trigger garbage
> collection.
> Seriously consider why this needs to be a separate thread instead of a
> separate app.
>
> HTH,
> Ginny
>
> "Martin"  wrote in message news:WKWvt.136194$I84.63382@fx07.fr7...
>
> Got quite a bit on the go now, but need a thread with data access, also
> it may need to run continually.
>
> Anything I need to be careful with please?
>
> Tahnks
>
> Martin

[toc] | [prev] | [next] | [standalone]


#5374

From"Ginny Caughey" <gcaughey@online.hotmail.com>
Date2013-06-18 12:41 -0400
Message-ID<51c08d89$0$1698$c3e8da3$14a0410e@news.astraweb.com>
In reply to#5371
I'm not sure what you mean by neatness of code, but I think you understand 
what I mean about threads being sort of the last choice to use. ;-)

Given that this is VO, I'd try very hard to make this a separate app instead 
of a separate thread. The code you're showing me uses manipulates strings, 
for example. It looks like it wants to do something on the UI thread too, 
which you can't do from a worker thread. Instead you could pass a Windows 
message to the UI thread, which its dispatcher could interpret in some way. 
I'm also not seeing where you open and close the database on the worker 
thread. You can't manipulate the same workarea safely across threads.

See my Serial class for an example of using a worker thread safely.

Ginny

"Martin"  wrote in message news:M9Xvt.159290$xf1.107935@fx16.fr7...

Thanks Ginny

The main reason is neatness of code and communications.

I will be sending the rack number in a PSZ in a struct but will need to
search a DBF for it.

This is the code I am converting, this is in XBase++, but need it in VO
2.8. AS you can see it is not especially long, and is stable, but I
can't link in huge amounts of VO into Xbase++

cBat := Left(cRack,10)
// Now we could monitor order or rack
IF TDelList->(DBSeek(cRack))
TBarCode->(OrdSetFocus(2))
TBarList->(OrdSetFocus(2))

// Check the order
cOrder := TDelList->DEL_Order
IF TOrder->(DBSeek(cOrder))
cCust := Torder->OD_CustNo
ELSE
cCust := 'xxxxxxxxxx'
ENDIF

lOk := .T.
DO WHILE TDellist->DEL_Key == cBat .AND. !TDellist->(EoF())
cOrder := TDelList->DEL_Order
IF TOrder->(DBSeek(cOrder))
IF cCust <> Torder->OD_CustNo
EXIT
ENDIF

// Check the barcodes
TBarCode->(DBSeek(cOrder))
DO WHILE TBarCode->BC_Order == cOrder .AND. !TBarCode->(EoF())
cBarcode := TBarCode->BC_Key

IF !TBarList->(DBSeek(cProc+cBarcode))
lOk := .F.
EXIT
ENDIF

IF TBarList->PL_Qty <= 0
lOk := .F.
EXIT
ENDIF

TBarCode->(DBSkip(1))
ENDDO
ENDIF
TDelList->(DBSkip(1))
ENDDO

IF lOk
// Fully loaded!!!!
// Hit_Key('fully loaded')

nPos := AT(cErr,'OPQRSTUVWXYZ')
SBeep(nPos,9,'WAV')
ENDIF

TBarCode->(OrdSetFocus(1))
TBarList->(OrdSetFocus(1))
ENDIF





On 18/06/2013 11:59, Ginny Caughey wrote:
> If you access DBF files, don't share the workarea with any other thread.
> Use normal multiuser access patterns.
> No dynamic data types such as strings that might trigger garbage
> collection.
> Seriously consider why this needs to be a separate thread instead of a
> separate app.
>
> HTH,
> Ginny
>
> "Martin"  wrote in message news:WKWvt.136194$I84.63382@fx07.fr7...
>
> Got quite a bit on the go now, but need a thread with data access, also
> it may need to run continually.
>
> Anything I need to be careful with please?
>
> Tahnks
>
> Martin 

[toc] | [prev] | [next] | [standalone]


#5378

FromMartin <spam@spam.spam>
Date2013-06-19 09:14 +0100
Message-ID<yLdwt.151237$OL1.2491@fx13.fr7>
In reply to#5374
Hello Ginny

That is XBase++ code!

See thread crashing messages for the VO Code

Thanks

Martin

On 18/06/2013 17:41, Ginny Caughey wrote:
> I'm not sure what you mean by neatness of code, but I think you
> understand what I mean about threads being sort of the last choice to
> use. ;-)
>
> Given that this is VO, I'd try very hard to make this a separate app
> instead of a separate thread. The code you're showing me uses
> manipulates strings, for example. It looks like it wants to do something
> on the UI thread too, which you can't do from a worker thread. Instead
> you could pass a Windows message to the UI thread, which its dispatcher
> could interpret in some way. I'm also not seeing where you open and
> close the database on the worker thread. You can't manipulate the same
> workarea safely across threads.
>
> See my Serial class for an example of using a worker thread safely.
>
> Ginny
>
> "Martin"  wrote in message news:M9Xvt.159290$xf1.107935@fx16.fr7...
>
> Thanks Ginny
>
> The main reason is neatness of code and communications.
>
> I will be sending the rack number in a PSZ in a struct but will need to
> search a DBF for it.
>
> This is the code I am converting, this is in XBase++, but need it in VO
> 2.8. AS you can see it is not especially long, and is stable, but I
> can't link in huge amounts of VO into Xbase++
>
> cBat := Left(cRack,10)
> // Now we could monitor order or rack
> IF TDelList->(DBSeek(cRack))
> TBarCode->(OrdSetFocus(2))
> TBarList->(OrdSetFocus(2))
>
> // Check the order
> cOrder := TDelList->DEL_Order
> IF TOrder->(DBSeek(cOrder))
> cCust := Torder->OD_CustNo
> ELSE
> cCust := 'xxxxxxxxxx'
> ENDIF
>
> lOk := .T.
> DO WHILE TDellist->DEL_Key == cBat .AND. !TDellist->(EoF())
> cOrder := TDelList->DEL_Order
> IF TOrder->(DBSeek(cOrder))
> IF cCust <> Torder->OD_CustNo
> EXIT
> ENDIF
>
> // Check the barcodes
> TBarCode->(DBSeek(cOrder))
> DO WHILE TBarCode->BC_Order == cOrder .AND. !TBarCode->(EoF())
> cBarcode := TBarCode->BC_Key
>
> IF !TBarList->(DBSeek(cProc+cBarcode))
> lOk := .F.
> EXIT
> ENDIF
>
> IF TBarList->PL_Qty <= 0
> lOk := .F.
> EXIT
> ENDIF
>
> TBarCode->(DBSkip(1))
> ENDDO
> ENDIF
> TDelList->(DBSkip(1))
> ENDDO
>
> IF lOk
> // Fully loaded!!!!
> // Hit_Key('fully loaded')
>
> nPos := AT(cErr,'OPQRSTUVWXYZ')
> SBeep(nPos,9,'WAV')
> ENDIF
>
> TBarCode->(OrdSetFocus(1))
> TBarList->(OrdSetFocus(1))
> ENDIF
>
>
>
>
>
> On 18/06/2013 11:59, Ginny Caughey wrote:
>> If you access DBF files, don't share the workarea with any other thread.
>> Use normal multiuser access patterns.
>> No dynamic data types such as strings that might trigger garbage
>> collection.
>> Seriously consider why this needs to be a separate thread instead of a
>> separate app.
>>
>> HTH,
>> Ginny
>>
>> "Martin"  wrote in message news:WKWvt.136194$I84.63382@fx07.fr7...
>>
>> Got quite a bit on the go now, but need a thread with data access, also
>> it may need to run continually.
>>
>> Anything I need to be careful with please?
>>
>> Tahnks
>>
>> Martin
>

[toc] | [prev] | [next] | [standalone]


#5379

From"Ginny Caughey" <gcaughey@online.hotmail.com>
Date2013-06-19 07:24 -0400
Message-ID<51c194b1$0$38134$c3e8da3$f6268168@news.astraweb.com>
In reply to#5378
I don't remember seeing the VO code that runs in a worker thread then. If 
you want to show it I may be able to make some suggestions. I had one app 
that ran 4 worker threads accessing DBF files 24x7 for several years at 
several sites, so it is certainly possible, but when I replaced that 
functionality with C# apps, I used separate processes rather than separate 
threads even though .NET has better thread handling than the VO runtime.

Ginny

"Martin"  wrote in message news:yLdwt.151237$OL1.2491@fx13.fr7...

Hello Ginny

That is XBase++ code!

See thread crashing messages for the VO Code

Thanks

Martin

On 18/06/2013 17:41, Ginny Caughey wrote:
> I'm not sure what you mean by neatness of code, but I think you
> understand what I mean about threads being sort of the last choice to
> use. ;-)
>
> Given that this is VO, I'd try very hard to make this a separate app
> instead of a separate thread. The code you're showing me uses
> manipulates strings, for example. It looks like it wants to do something
> on the UI thread too, which you can't do from a worker thread. Instead
> you could pass a Windows message to the UI thread, which its dispatcher
> could interpret in some way. I'm also not seeing where you open and
> close the database on the worker thread. You can't manipulate the same
> workarea safely across threads.
>
> See my Serial class for an example of using a worker thread safely.
>
> Ginny
>
> "Martin"  wrote in message news:M9Xvt.159290$xf1.107935@fx16.fr7...
>
> Thanks Ginny
>
> The main reason is neatness of code and communications.
>
> I will be sending the rack number in a PSZ in a struct but will need to
> search a DBF for it.
>
> This is the code I am converting, this is in XBase++, but need it in VO
> 2.8. AS you can see it is not especially long, and is stable, but I
> can't link in huge amounts of VO into Xbase++
>
> cBat := Left(cRack,10)
> // Now we could monitor order or rack
> IF TDelList->(DBSeek(cRack))
> TBarCode->(OrdSetFocus(2))
> TBarList->(OrdSetFocus(2))
>
> // Check the order
> cOrder := TDelList->DEL_Order
> IF TOrder->(DBSeek(cOrder))
> cCust := Torder->OD_CustNo
> ELSE
> cCust := 'xxxxxxxxxx'
> ENDIF
>
> lOk := .T.
> DO WHILE TDellist->DEL_Key == cBat .AND. !TDellist->(EoF())
> cOrder := TDelList->DEL_Order
> IF TOrder->(DBSeek(cOrder))
> IF cCust <> Torder->OD_CustNo
> EXIT
> ENDIF
>
> // Check the barcodes
> TBarCode->(DBSeek(cOrder))
> DO WHILE TBarCode->BC_Order == cOrder .AND. !TBarCode->(EoF())
> cBarcode := TBarCode->BC_Key
>
> IF !TBarList->(DBSeek(cProc+cBarcode))
> lOk := .F.
> EXIT
> ENDIF
>
> IF TBarList->PL_Qty <= 0
> lOk := .F.
> EXIT
> ENDIF
>
> TBarCode->(DBSkip(1))
> ENDDO
> ENDIF
> TDelList->(DBSkip(1))
> ENDDO
>
> IF lOk
> // Fully loaded!!!!
> // Hit_Key('fully loaded')
>
> nPos := AT(cErr,'OPQRSTUVWXYZ')
> SBeep(nPos,9,'WAV')
> ENDIF
>
> TBarCode->(OrdSetFocus(1))
> TBarList->(OrdSetFocus(1))
> ENDIF
>
>
>
>
>
> On 18/06/2013 11:59, Ginny Caughey wrote:
>> If you access DBF files, don't share the workarea with any other thread.
>> Use normal multiuser access patterns.
>> No dynamic data types such as strings that might trigger garbage
>> collection.
>> Seriously consider why this needs to be a separate thread instead of a
>> separate app.
>>
>> HTH,
>> Ginny
>>
>> "Martin"  wrote in message news:WKWvt.136194$I84.63382@fx07.fr7...
>>
>> Got quite a bit on the go now, but need a thread with data access, also
>> it may need to run continually.
>>
>> Anything I need to be careful with please?
>>
>> Tahnks
>>
>> Martin
> 

[toc] | [prev] | [next] | [standalone]


#5380

FromMartin <spam@spam.spam>
Date2013-06-19 12:40 +0100
Message-ID<vMgwt.107261$4C2.78184@fx23.fr7>
In reply to#5379
Here we go Ginny


Thanks

Martin


FUNCTION DelMonitor (ptrCtrl AS PTR) AS LONG STRICT

LOCAL TBarList    AS bcBarList, ;
       TBarCode    AS bcBarCode, ;
       TOrder    AS bcOrder, ;
       TDelList    AS bcDelList, ; //, a as csocket
       strCtrl    AS CheckThreadControl, ;
       pszRack    AS PSZ, ;
       pszBat    AS PSZ, ;
       pszProc    AS PSZ, ;
       cOrder    AS STRING, ;
       cCust        AS STRING, ;
       cBarCode    AS STRING, ;
       cProc        AS STRING, ;
       nRack        AS DWORD, ;
       lOk        AS LOGIC, ;
       nCount    AS DWORD

strCtrl    := ptrCtrl
flog('a')
IF strCtrl.lLive
     RETURN 0
ENDIF
flog('b')

DynLock()
strCtrl.lLive    := TRUE

//    GUI Less servers
TBarList    := bcBarList{}
TBarCode    := bcBarCode{}
TOrder        := bcOrder{}
TDelList    := bcDelList{}

nCount        := 0

//    big loop in here
DO WHILE !strCtrl.lToClose

     IF nCount > 3
         EXIT
     ENDIF

     IF strCtrl.lToClose
         EXIT
     ENDIF

     IF strCtrl.lWait
//        pause here
         sleep(200)
         nCount    ++
         LOOP
     ENDIF

//    If I have data check the batch
     nRack    := GetpszRack(strCtrl)
     IF nRack = 0
         nCount    ++
         sleep(200)
         LOOP
     ENDIF

     DO CASE
         CASE nRack = 1
             pszRack    := strCtrl.pszRack1
             pszBat    := strCtrl.pszBat1
             pszProc    := strCtrl.pszProc1

             strCtrl.pszRack1    := Null_PSZ
         CASE nRack = 2
             pszRack    := strCtrl.pszRack2
             pszBat    := strCtrl.pszBat2
             pszProc    := strCtrl.pszProc2

             strCtrl.pszRack2    := Null_PSZ
         CASE nRack = 3
             pszRack    := strCtrl.pszRack3
             pszBat    := strCtrl.pszBat3
             pszProc    := strCtrl.pszProc3

             strCtrl.pszRack3    := Null_PSZ
     ENDCASE

     nCount    := 0

     IF TDelList:Seek(pszRack)
         TBarCode:SetOrder(2)
         TBarList:SetOrder(2)

//        Check the order
         cOrder    := TDelList:FieldGet(#DEL_Order)

         IF TOrder:Seek(cOrder)
             cCust    := Torder:FieldGet(#OD_CustNo)
         ELSE
             cCust    := 'xxxxxxxxxx'
         ENDIF

         cProc    := PSZ2String(pszProc)

         lOk    := TRUE
         DO WHILE TDellist:FieldGet(#DEL_Key) == pszBat .AND. !TDellist:EoF
             cOrder    := TDelList:FieldGet(#DEL_Order)
             IF TOrder:Seek(cOrder)

                 IF cCust <> Torder:FieldGet(#OD_CustNo)
                     EXIT
                 ENDIF

//                Check the barcodes
                 TBarCode:Seek(cOrder)
                 DO WHILE TBarCode:FieldGet(#BC_Order) == cOrder .AND. 
!TBarCode:EoF
                     cBarcode    := TBarCode:FieldGet(#BC_Key)

                     IF !TBarList:Seek(cProc+cBarcode)
                         lOk    := FALSE
                         EXIT
                     ENDIF

                     IF TBarList:FieldGet(#PL_Qty) <= 0
                         lOk    := FALSE
                         EXIT
                     ENDIF

                     TBarCode:Skip(1)
                 ENDDO
             ENDIF
             TDelList:Skip(1)
         ENDDO

         IF lOk
             PostMessage(strCtrl.hWindow,WM_APP+110,nRack,0)
             flog('ok')
         ELSE
             PostMessage(strCtrl.hWindow,WM_APP+111,nRack,0)
             flog('not')
         ENDIF

         TBarCode:SetOrder(1)
         TBarList:SetOrder(1)

      ENDIF

ENDDO

DynUnlock()

TDelList:Close()
TOrder:Close()
TBarCode:Close()
TBarList:Close()

strCtrl.lLive    := FALSE
flog('c')

RETURN 0


On 19/06/2013 12:24, Ginny Caughey wrote:
> I don't remember seeing the VO code that runs in a worker thread then.
> If you want to show it I may be able to make some suggestions. I had one
> app that ran 4 worker threads accessing DBF files 24x7 for several years
> at several sites, so it is certainly possible, but when I replaced that
> functionality with C# apps, I used separate processes rather than
> separate threads even though .NET has better thread handling than the VO
> runtime.
>
> Ginny
>
> "Martin"  wrote in message news:yLdwt.151237$OL1.2491@fx13.fr7...
>
> Hello Ginny
>
> That is XBase++ code!
>
> See thread crashing messages for the VO Code
>
> Thanks
>
> Martin
>
> On 18/06/2013 17:41, Ginny Caughey wrote:
>> I'm not sure what you mean by neatness of code, but I think you
>> understand what I mean about threads being sort of the last choice to
>> use. ;-)
>>
>> Given that this is VO, I'd try very hard to make this a separate app
>> instead of a separate thread. The code you're showing me uses
>> manipulates strings, for example. It looks like it wants to do something
>> on the UI thread too, which you can't do from a worker thread. Instead
>> you could pass a Windows message to the UI thread, which its dispatcher
>> could interpret in some way. I'm also not seeing where you open and
>> close the database on the worker thread. You can't manipulate the same
>> workarea safely across threads.
>>
>> See my Serial class for an example of using a worker thread safely.
>>
>> Ginny
>>
>> "Martin"  wrote in message news:M9Xvt.159290$xf1.107935@fx16.fr7...
>>
>> Thanks Ginny
>>
>> The main reason is neatness of code and communications.
>>
>> I will be sending the rack number in a PSZ in a struct but will need to
>> search a DBF for it.
>>
>> This is the code I am converting, this is in XBase++, but need it in VO
>> 2.8. AS you can see it is not especially long, and is stable, but I
>> can't link in huge amounts of VO into Xbase++
>>
>> cBat := Left(cRack,10)
>> // Now we could monitor order or rack
>> IF TDelList->(DBSeek(cRack))
>> TBarCode->(OrdSetFocus(2))
>> TBarList->(OrdSetFocus(2))
>>
>> // Check the order
>> cOrder := TDelList->DEL_Order
>> IF TOrder->(DBSeek(cOrder))
>> cCust := Torder->OD_CustNo
>> ELSE
>> cCust := 'xxxxxxxxxx'
>> ENDIF
>>
>> lOk := .T.
>> DO WHILE TDellist->DEL_Key == cBat .AND. !TDellist->(EoF())
>> cOrder := TDelList->DEL_Order
>> IF TOrder->(DBSeek(cOrder))
>> IF cCust <> Torder->OD_CustNo
>> EXIT
>> ENDIF
>>
>> // Check the barcodes
>> TBarCode->(DBSeek(cOrder))
>> DO WHILE TBarCode->BC_Order == cOrder .AND. !TBarCode->(EoF())
>> cBarcode := TBarCode->BC_Key
>>
>> IF !TBarList->(DBSeek(cProc+cBarcode))
>> lOk := .F.
>> EXIT
>> ENDIF
>>
>> IF TBarList->PL_Qty <= 0
>> lOk := .F.
>> EXIT
>> ENDIF
>>
>> TBarCode->(DBSkip(1))
>> ENDDO
>> ENDIF
>> TDelList->(DBSkip(1))
>> ENDDO
>>
>> IF lOk
>> // Fully loaded!!!!
>> // Hit_Key('fully loaded')
>>
>> nPos := AT(cErr,'OPQRSTUVWXYZ')
>> SBeep(nPos,9,'WAV')
>> ENDIF
>>
>> TBarCode->(OrdSetFocus(1))
>> TBarList->(OrdSetFocus(1))
>> ENDIF
>>
>>
>>
>>
>>
>> On 18/06/2013 11:59, Ginny Caughey wrote:
>>> If you access DBF files, don't share the workarea with any other thread.
>>> Use normal multiuser access patterns.
>>> No dynamic data types such as strings that might trigger garbage
>>> collection.
>>> Seriously consider why this needs to be a separate thread instead of a
>>> separate app.
>>>
>>> HTH,
>>> Ginny
>>>
>>> "Martin"  wrote in message news:WKWvt.136194$I84.63382@fx07.fr7...
>>>
>>> Got quite a bit on the go now, but need a thread with data access, also
>>> it may need to run continually.
>>>
>>> Anything I need to be careful with please?
>>>
>>> Tahnks
>>>
>>> Martin
>>
>

[toc] | [prev] | [next] | [standalone]


#5382

From"Ginny Caughey" <gcaughey@online.hotmail.com>
Date2013-06-19 10:02 -0400
Message-ID<51c1b9c8$0$57971$c3e8da3$eb767761@news.astraweb.com>
In reply to#5380
Martin,

I'm really not seeing anything obviously wrong here. Have you tried it 
without the Dynlock/Dynunlock? Here's my threaded code that ran without 
issues for several years. Maybe you'll spot something useful:

FUNCTION RunPollingLoop( pInfo AS WatchInfo ) AS DWORD PASCAL    // Threaded 
function
    LOCAL uMsg IS _winMsg    // used by thread message loop
    LOCAL aParity AS ARRAY
    LOCAL i AS INT
    LOCAL cScale, cParity AS STRING
    LOCAL nWeight, nTopWeight, nMinimumWt, nDelay AS INT
    LOCAL dwStop AS DWORD
    LOCAL dDate AS DATE
    LOCAL cTime AS STRING
    LOCAL oReader AS ScaleWatcher    // object that actually reads the scale 
and performs NTEP weight validation
    LOCAL control, watchman, wconfig AS DWORD    // workareas for dbf files
    LOCAL lError AS LOGIC

    // Update status bar with scale started text
    PostMessage(pInfo.hWnd, MSG_StartStop, pInfo.ScaleNumber, ScaleStarted)

    // read paramters for this scale from wconfig and control files
    aParity := { {"E", EvenParity}, ;
                {"M", MarkParity}, ;
                {"N", NoParity}, ;
                {"O", OddParity}, ;
                {"S", SpaceParity}     }

    BEGIN SEQUENCE
        IF !OpenDbfQuiet("control")
            BREAK
        ENDIF
        control := DBGETSELECT()
        IF !OpenDbfQuiet("wconfig")
            BREAK
        ENDIF
        wconfig := DBGETSELECT()
        IF !OpenDbfQuiet("watchman")
            BREAK
        ENDIF
        watchman := DBGETSELECT()
    RECOVER
        lError := TRUE
        HandleError("Unable to open a file needed to run Watchman Mode 
processing.")
        IF control > 0
            DBSELECTAREA(control)
            DBCLOSEAREA()
        ENDIF
        IF wconfig > 0
            DBSELECTAREA(wconfig)
            DBCLOSEAREA()
        ENDIF
        IF watchman > 0
            DBSELECTAREA(watchman)
            DBCLOSEAREA()
        ENDIF
    END SEQUENCE

    IF lError
        RETURN 0
    ENDIF

    PostMessage(pInfo.hWnd, MSG_GettingData, pInfo.ScaleNumber, 0)
    oReader := ScaleWatcher{pInfo.hWnd}
    oReader:CommPort := "Com"+ NTrim(pInfo.PortNumber)
    Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Getting info for scale")

    // Get info for this scale port from control file
    cScale := Str(pInfo.ScaleNumber,1,0)
    nMinimumWt := (wconfig)->minimumwt
    nDelay := (wconfig)->interval
    (wconfig)->(DBCLOSEAREA())

    oReader:Baud := (control)->(FIELDGET(FieldPos("baud"+cScale)))
    oReader:Databits := (control)->(FIELDGET(FieldPos("databits"+cScale)))
    oReader:Stopbits := (control)->(FIELDGET(FieldPos("stopbits"+cScale)))
    IF oReader:Stopbits = 1
        oReader:Stopbits := OneStopBit    // convert to Windows value (2 = 
TwoStopBits already)
    ENDIF
    cParity := (control)->(FIELDGET(FieldPos("parity"+cScale)))
    i := AScan(aParity, {|aVal| aVal[1] = cParity})
    IF i > 0
        oReader:Parity := aParity[i,2]
    ELSE
        oReader:Parity := NoParity
    ENDIF
    oReader:Buffsize := (control)->(FIELDGET(FieldPos("buffsize"+cScale)))
    oReader:WtBegin :=  (control)->(FIELDGET(FieldPos("wtbegin"+cScale)))
    oReader:WtLength := (control)->(FIELDGET(FieldPos("wtlength"+cScale)))
    oReader:CheckChar := (control)->(FIELDGET(FieldPos("poll1chr"+cScale)))
    oReader:CheckPosition := 
(control)->(FIELDGET(FieldPos("poll2chr"+cScale)))
    oReader:MaxRetries := (control)->(FIELDGET(FieldPos("poll3chr"+cScale)))
    oReader:MotionChar := (control)->(FIELDGET(FieldPos("poll4chr"+cScale)))
    oReader:MotionByte := (control)->(FIELDGET(FieldPos("ack"+cScale)))
    oReader:GrossLoc := (control)->(FIELDGET(FieldPos("grossloc"+cScale)))
    oReader:UnitLoc := (control)->(FIELDGET(FieldPos("unitloc"+cScale)))
    oReader:ScaleUnit := (control)->(FIELDGET(FieldPos("scaleunit")))
    (control)->(DBCLOSEAREA())

    // Run polling loop until WM_QUIT received from primary thread
    // Polling is a two step process here:
    //    1. Sample every nDelay seconds for a weigh large enough to 
indicate a vehicle
    //    2. Once a vehicle is on the scale, sample at 1/10 second intervals 
to catch maximum weight
    WHILE TRUE
        Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - In polling loop")
        //PostMessage(pInfo.hWnd, MSG_Polling, pInfo.ScaleNumber, 0)
        IF PeekMessage(@uMsg, 0, 0, 0, PM_REMOVE)    // PeekMessage returns 
true if any messages in queue
            IF uMsg.message == WM_QUIT
                EXIT
            ENDIF
        ENDIF
        Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Getting first 
weight")
        nWeight := oReader:ReadScale()
        Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - nWeight is 
"+NTrim(nWeight))
        IF oReader:CancelRequested
            EXIT
        ENDIF
        IF nWeight = -1    // Error occurred
            PostMessage(pInfo.hWnd, MSG_ScaleError, pInfo.ScaleNumber, 0)
        ELSEIF nWeight < nMinimumWt
            dwStop := GetTickCountLow()+DWORD(nDelay * 1000)
            //PostMessage(pInfo.hWnd, MSG_Polling, pInfo.ScaleNumber, 0)
            WHILE GetTickCountLow() <= dwStop
                IF PeekMessage(@uMsg, 0, 0, 0, PM_REMOVE)
                    IF uMsg.message == WM_QUIT
                        EXIT
                    ENDIF
                ENDIF
            END
        ELSE
            // We have a vehicle on scale
            // Sample every 1/10 second until its maximum weight is captured
            PostMessage(pInfo.hWnd, MSG_Sampling, pInfo.ScaleNumber, 0)
            nTopWeight := nWeight
            dDate := Today()
            cTime := Time24()
            WHILE TRUE
                IF PeekMessage(@uMsg, 0, 0, 0, PM_NOREMOVE)
                    IF uMsg.message == WM_QUIT
                        EXIT
                    ENDIF
                ENDIF
                Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Testing for 
maximum weight")
                nWeight := oReader:ReadScale()
                IF oReader:CancelRequested
                    EXIT
                ENDIF
                IF nWeight < nMinimumWt .AND. !oReader:MotionDetected
                    EXIT
                ENDIF
                IF nWeight > nTopWeight
                    nTopWeight := nWeight
                    dDate := Today()
                    cTime := Time24()
                ENDIF
                Sleep(100)    // give time slice to other threads for 1/10 
second
            END
            IF uMsg.message != WM_QUIT .AND. !oReader:CancelRequested
                // Write out weight to file using file sharing
                IF (watchman)->(AddDbfQuiet())
                    (watchman)->today := dDate
                    (watchman)->time24 := cTime
                    (watchman)->weight := nTopWeight
                    (watchman)->scaleno := Str(pInfo.ScaleNumber,1,0)
                    (watchman)->(DBCOMMIT())
                    (watchman)->(DBUNLOCK())
                ELSE
                    HandleError("Unable to add a record to the watchman 
file.")
                ENDIF
            ELSE
                EXIT
            ENDIF
        ENDIF
        IF uMsg.message == WM_QUIT .OR. oReader:CancelRequested
            EXIT
        ENDIF
    END
    Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Shutting down thread")
    (watchman)->(DBCLOSEAREA())
    RETURN 0
FUNCTION Output( s AS STRING ) AS VOID PASCAL    // thread-safe way to write 
to log file
    IF hDebug != NULL_PTR
        EnterCriticalSection(@CS_DEBUG)
        FWriteLine(hDebug, s)
        LeaveCriticalSection(@CS_DEBUG)
    ENDIF
    RETURN
FUNCTION HandleError(cError AS STRING) AS VOID PASCAL
    LOCAL hFile AS PTR

    // Thread-safe write to log file
    EnterCriticalSection(@CS_WATCHERR)
    IF File(GetDefault()+"watcherr.log")
        hFile := FOpen(GetDefault()+"watcherr.log", FO_READWRITE)
        FSeek(hFile, 0, FS_END)
    ELSE
        hFile := FCreate(GetDefault()+"watcherr.log")
    ENDIF
    IF hFile != F_ERROR
        FWrite(hFile, DToC(Today())+" "+Time24()+" 
"+cError+_CHR(13)+_CHR(10))
        FClose(hFile)
    ENDIF
    LeaveCriticalSection(@CS_WATCHERR)
Ginny

"Martin"  wrote in message news:vMgwt.107261$4C2.78184@fx23.fr7...

Here we go Ginny


Thanks

Martin


FUNCTION DelMonitor (ptrCtrl AS PTR) AS LONG STRICT

LOCAL TBarList    AS bcBarList, ;
       TBarCode    AS bcBarCode, ;
       TOrder    AS bcOrder, ;
       TDelList    AS bcDelList, ; //, a as csocket
       strCtrl    AS CheckThreadControl, ;
       pszRack    AS PSZ, ;
       pszBat    AS PSZ, ;
       pszProc    AS PSZ, ;
       cOrder    AS STRING, ;
       cCust        AS STRING, ;
       cBarCode    AS STRING, ;
       cProc        AS STRING, ;
       nRack        AS DWORD, ;
       lOk        AS LOGIC, ;
       nCount    AS DWORD

strCtrl    := ptrCtrl
flog('a')
IF strCtrl.lLive
     RETURN 0
ENDIF
flog('b')

DynLock()
strCtrl.lLive    := TRUE

//    GUI Less servers
TBarList    := bcBarList{}
TBarCode    := bcBarCode{}
TOrder        := bcOrder{}
TDelList    := bcDelList{}

nCount        := 0

//    big loop in here
DO WHILE !strCtrl.lToClose

     IF nCount > 3
         EXIT
     ENDIF

     IF strCtrl.lToClose
         EXIT
     ENDIF

     IF strCtrl.lWait
//        pause here
         sleep(200)
         nCount    ++
         LOOP
     ENDIF

//    If I have data check the batch
     nRack    := GetpszRack(strCtrl)
     IF nRack = 0
         nCount    ++
         sleep(200)
         LOOP
     ENDIF

     DO CASE
         CASE nRack = 1
             pszRack    := strCtrl.pszRack1
             pszBat    := strCtrl.pszBat1
             pszProc    := strCtrl.pszProc1

             strCtrl.pszRack1    := Null_PSZ
         CASE nRack = 2
             pszRack    := strCtrl.pszRack2
             pszBat    := strCtrl.pszBat2
             pszProc    := strCtrl.pszProc2

             strCtrl.pszRack2    := Null_PSZ
         CASE nRack = 3
             pszRack    := strCtrl.pszRack3
             pszBat    := strCtrl.pszBat3
             pszProc    := strCtrl.pszProc3

             strCtrl.pszRack3    := Null_PSZ
     ENDCASE

     nCount    := 0

     IF TDelList:Seek(pszRack)
         TBarCode:SetOrder(2)
         TBarList:SetOrder(2)

//        Check the order
         cOrder    := TDelList:FieldGet(#DEL_Order)

         IF TOrder:Seek(cOrder)
             cCust    := Torder:FieldGet(#OD_CustNo)
         ELSE
             cCust    := 'xxxxxxxxxx'
         ENDIF

         cProc    := PSZ2String(pszProc)

         lOk    := TRUE
         DO WHILE TDellist:FieldGet(#DEL_Key) == pszBat .AND. !TDellist:EoF
             cOrder    := TDelList:FieldGet(#DEL_Order)
             IF TOrder:Seek(cOrder)

                 IF cCust <> Torder:FieldGet(#OD_CustNo)
                     EXIT
                 ENDIF

//                Check the barcodes
                 TBarCode:Seek(cOrder)
                 DO WHILE TBarCode:FieldGet(#BC_Order) == cOrder .AND.
!TBarCode:EoF
                     cBarcode    := TBarCode:FieldGet(#BC_Key)

                     IF !TBarList:Seek(cProc+cBarcode)
                         lOk    := FALSE
                         EXIT
                     ENDIF

                     IF TBarList:FieldGet(#PL_Qty) <= 0
                         lOk    := FALSE
                         EXIT
                     ENDIF

                     TBarCode:Skip(1)
                 ENDDO
             ENDIF
             TDelList:Skip(1)
         ENDDO

         IF lOk
             PostMessage(strCtrl.hWindow,WM_APP+110,nRack,0)
             flog('ok')
         ELSE
             PostMessage(strCtrl.hWindow,WM_APP+111,nRack,0)
             flog('not')
         ENDIF

         TBarCode:SetOrder(1)
         TBarList:SetOrder(1)

      ENDIF

ENDDO

DynUnlock()

TDelList:Close()
TOrder:Close()
TBarCode:Close()
TBarList:Close()

strCtrl.lLive    := FALSE
flog('c')

RETURN 0


On 19/06/2013 12:24, Ginny Caughey wrote:
> I don't remember seeing the VO code that runs in a worker thread then.
> If you want to show it I may be able to make some suggestions. I had one
> app that ran 4 worker threads accessing DBF files 24x7 for several years
> at several sites, so it is certainly possible, but when I replaced that
> functionality with C# apps, I used separate processes rather than
> separate threads even though .NET has better thread handling than the VO
> runtime.
>
> Ginny
>
> "Martin"  wrote in message news:yLdwt.151237$OL1.2491@fx13.fr7...
>
> Hello Ginny
>
> That is XBase++ code!
>
> See thread crashing messages for the VO Code
>
> Thanks
>
> Martin
>
> On 18/06/2013 17:41, Ginny Caughey wrote:
>> I'm not sure what you mean by neatness of code, but I think you
>> understand what I mean about threads being sort of the last choice to
>> use. ;-)
>>
>> Given that this is VO, I'd try very hard to make this a separate app
>> instead of a separate thread. The code you're showing me uses
>> manipulates strings, for example. It looks like it wants to do something
>> on the UI thread too, which you can't do from a worker thread. Instead
>> you could pass a Windows message to the UI thread, which its dispatcher
>> could interpret in some way. I'm also not seeing where you open and
>> close the database on the worker thread. You can't manipulate the same
>> workarea safely across threads.
>>
>> See my Serial class for an example of using a worker thread safely.
>>
>> Ginny
>>
>> "Martin"  wrote in message news:M9Xvt.159290$xf1.107935@fx16.fr7...
>>
>> Thanks Ginny
>>
>> The main reason is neatness of code and communications.
>>
>> I will be sending the rack number in a PSZ in a struct but will need to
>> search a DBF for it.
>>
>> This is the code I am converting, this is in XBase++, but need it in VO
>> 2.8. AS you can see it is not especially long, and is stable, but I
>> can't link in huge amounts of VO into Xbase++
>>
>> cBat := Left(cRack,10)
>> // Now we could monitor order or rack
>> IF TDelList->(DBSeek(cRack))
>> TBarCode->(OrdSetFocus(2))
>> TBarList->(OrdSetFocus(2))
>>
>> // Check the order
>> cOrder := TDelList->DEL_Order
>> IF TOrder->(DBSeek(cOrder))
>> cCust := Torder->OD_CustNo
>> ELSE
>> cCust := 'xxxxxxxxxx'
>> ENDIF
>>
>> lOk := .T.
>> DO WHILE TDellist->DEL_Key == cBat .AND. !TDellist->(EoF())
>> cOrder := TDelList->DEL_Order
>> IF TOrder->(DBSeek(cOrder))
>> IF cCust <> Torder->OD_CustNo
>> EXIT
>> ENDIF
>>
>> // Check the barcodes
>> TBarCode->(DBSeek(cOrder))
>> DO WHILE TBarCode->BC_Order == cOrder .AND. !TBarCode->(EoF())
>> cBarcode := TBarCode->BC_Key
>>
>> IF !TBarList->(DBSeek(cProc+cBarcode))
>> lOk := .F.
>> EXIT
>> ENDIF
>>
>> IF TBarList->PL_Qty <= 0
>> lOk := .F.
>> EXIT
>> ENDIF
>>
>> TBarCode->(DBSkip(1))
>> ENDDO
>> ENDIF
>> TDelList->(DBSkip(1))
>> ENDDO
>>
>> IF lOk
>> // Fully loaded!!!!
>> // Hit_Key('fully loaded')
>>
>> nPos := AT(cErr,'OPQRSTUVWXYZ')
>> SBeep(nPos,9,'WAV')
>> ENDIF
>>
>> TBarCode->(OrdSetFocus(1))
>> TBarList->(OrdSetFocus(1))
>> ENDIF
>>
>>
>>
>>
>>
>> On 18/06/2013 11:59, Ginny Caughey wrote:
>>> If you access DBF files, don't share the workarea with any other thread.
>>> Use normal multiuser access patterns.
>>> No dynamic data types such as strings that might trigger garbage
>>> collection.
>>> Seriously consider why this needs to be a separate thread instead of a
>>> separate app.
>>>
>>> HTH,
>>> Ginny
>>>
>>> "Martin"  wrote in message news:WKWvt.136194$I84.63382@fx07.fr7...
>>>
>>> Got quite a bit on the go now, but need a thread with data access, also
>>> it may need to run continually.
>>>
>>> Anything I need to be careful with please?
>>>
>>> Tahnks
>>>
>>> Martin
>>
> 

[toc] | [prev] | [next] | [standalone]


#5385

FromMartin <spam@spam.spam>
Date2013-06-19 17:07 +0100
Message-ID<QGkwt.122934$G56.87814@fx32.fr7>
In reply to#5382
Very interesting, you are using direct DBF rather than servers, I will 
try that thankyou

On 19/06/2013 15:02, Ginny Caughey wrote:
> Martin,
>
> I'm really not seeing anything obviously wrong here. Have you tried it
> without the Dynlock/Dynunlock? Here's my threaded code that ran without
> issues for several years. Maybe you'll spot something useful:
>
> FUNCTION RunPollingLoop( pInfo AS WatchInfo ) AS DWORD PASCAL    //
> Threaded function
>     LOCAL uMsg IS _winMsg    // used by thread message loop
>     LOCAL aParity AS ARRAY
>     LOCAL i AS INT
>     LOCAL cScale, cParity AS STRING
>     LOCAL nWeight, nTopWeight, nMinimumWt, nDelay AS INT
>     LOCAL dwStop AS DWORD
>     LOCAL dDate AS DATE
>     LOCAL cTime AS STRING
>     LOCAL oReader AS ScaleWatcher    // object that actually reads the
> scale and performs NTEP weight validation
>     LOCAL control, watchman, wconfig AS DWORD    // workareas for dbf files
>     LOCAL lError AS LOGIC
>
>     // Update status bar with scale started text
>     PostMessage(pInfo.hWnd, MSG_StartStop, pInfo.ScaleNumber, ScaleStarted)
>
>     // read paramters for this scale from wconfig and control files
>     aParity := { {"E", EvenParity}, ;
>                 {"M", MarkParity}, ;
>                 {"N", NoParity}, ;
>                 {"O", OddParity}, ;
>                 {"S", SpaceParity}     }
>
>     BEGIN SEQUENCE
>         IF !OpenDbfQuiet("control")
>             BREAK
>         ENDIF
>         control := DBGETSELECT()
>         IF !OpenDbfQuiet("wconfig")
>             BREAK
>         ENDIF
>         wconfig := DBGETSELECT()
>         IF !OpenDbfQuiet("watchman")
>             BREAK
>         ENDIF
>         watchman := DBGETSELECT()
>     RECOVER
>         lError := TRUE
>         HandleError("Unable to open a file needed to run Watchman Mode
> processing.")
>         IF control > 0
>             DBSELECTAREA(control)
>             DBCLOSEAREA()
>         ENDIF
>         IF wconfig > 0
>             DBSELECTAREA(wconfig)
>             DBCLOSEAREA()
>         ENDIF
>         IF watchman > 0
>             DBSELECTAREA(watchman)
>             DBCLOSEAREA()
>         ENDIF
>     END SEQUENCE
>
>     IF lError
>         RETURN 0
>     ENDIF
>
>     PostMessage(pInfo.hWnd, MSG_GettingData, pInfo.ScaleNumber, 0)
>     oReader := ScaleWatcher{pInfo.hWnd}
>     oReader:CommPort := "Com"+ NTrim(pInfo.PortNumber)
>     Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Getting info for scale")
>
>     // Get info for this scale port from control file
>     cScale := Str(pInfo.ScaleNumber,1,0)
>     nMinimumWt := (wconfig)->minimumwt
>     nDelay := (wconfig)->interval
>     (wconfig)->(DBCLOSEAREA())
>
>     oReader:Baud := (control)->(FIELDGET(FieldPos("baud"+cScale)))
>     oReader:Databits := (control)->(FIELDGET(FieldPos("databits"+cScale)))
>     oReader:Stopbits := (control)->(FIELDGET(FieldPos("stopbits"+cScale)))
>     IF oReader:Stopbits = 1
>         oReader:Stopbits := OneStopBit    // convert to Windows value (2
> = TwoStopBits already)
>     ENDIF
>     cParity := (control)->(FIELDGET(FieldPos("parity"+cScale)))
>     i := AScan(aParity, {|aVal| aVal[1] = cParity})
>     IF i > 0
>         oReader:Parity := aParity[i,2]
>     ELSE
>         oReader:Parity := NoParity
>     ENDIF
>     oReader:Buffsize := (control)->(FIELDGET(FieldPos("buffsize"+cScale)))
>     oReader:WtBegin :=  (control)->(FIELDGET(FieldPos("wtbegin"+cScale)))
>     oReader:WtLength := (control)->(FIELDGET(FieldPos("wtlength"+cScale)))
>     oReader:CheckChar := (control)->(FIELDGET(FieldPos("poll1chr"+cScale)))
>     oReader:CheckPosition :=
> (control)->(FIELDGET(FieldPos("poll2chr"+cScale)))
>     oReader:MaxRetries :=
> (control)->(FIELDGET(FieldPos("poll3chr"+cScale)))
>     oReader:MotionChar :=
> (control)->(FIELDGET(FieldPos("poll4chr"+cScale)))
>     oReader:MotionByte := (control)->(FIELDGET(FieldPos("ack"+cScale)))
>     oReader:GrossLoc := (control)->(FIELDGET(FieldPos("grossloc"+cScale)))
>     oReader:UnitLoc := (control)->(FIELDGET(FieldPos("unitloc"+cScale)))
>     oReader:ScaleUnit := (control)->(FIELDGET(FieldPos("scaleunit")))
>     (control)->(DBCLOSEAREA())
>
>     // Run polling loop until WM_QUIT received from primary thread
>     // Polling is a two step process here:
>     //    1. Sample every nDelay seconds for a weigh large enough to
> indicate a vehicle
>     //    2. Once a vehicle is on the scale, sample at 1/10 second
> intervals to catch maximum weight
>     WHILE TRUE
>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - In polling loop")
>         //PostMessage(pInfo.hWnd, MSG_Polling, pInfo.ScaleNumber, 0)
>         IF PeekMessage(@uMsg, 0, 0, 0, PM_REMOVE)    // PeekMessage
> returns true if any messages in queue
>             IF uMsg.message == WM_QUIT
>                 EXIT
>             ENDIF
>         ENDIF
>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Getting first
> weight")
>         nWeight := oReader:ReadScale()
>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - nWeight is
> "+NTrim(nWeight))
>         IF oReader:CancelRequested
>             EXIT
>         ENDIF
>         IF nWeight = -1    // Error occurred
>             PostMessage(pInfo.hWnd, MSG_ScaleError, pInfo.ScaleNumber, 0)
>         ELSEIF nWeight < nMinimumWt
>             dwStop := GetTickCountLow()+DWORD(nDelay * 1000)
>             //PostMessage(pInfo.hWnd, MSG_Polling, pInfo.ScaleNumber, 0)
>             WHILE GetTickCountLow() <= dwStop
>                 IF PeekMessage(@uMsg, 0, 0, 0, PM_REMOVE)
>                     IF uMsg.message == WM_QUIT
>                         EXIT
>                     ENDIF
>                 ENDIF
>             END
>         ELSE
>             // We have a vehicle on scale
>             // Sample every 1/10 second until its maximum weight is
> captured
>             PostMessage(pInfo.hWnd, MSG_Sampling, pInfo.ScaleNumber, 0)
>             nTopWeight := nWeight
>             dDate := Today()
>             cTime := Time24()
>             WHILE TRUE
>                 IF PeekMessage(@uMsg, 0, 0, 0, PM_NOREMOVE)
>                     IF uMsg.message == WM_QUIT
>                         EXIT
>                     ENDIF
>                 ENDIF
>                 Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Testing
> for maximum weight")
>                 nWeight := oReader:ReadScale()
>                 IF oReader:CancelRequested
>                     EXIT
>                 ENDIF
>                 IF nWeight < nMinimumWt .AND. !oReader:MotionDetected
>                     EXIT
>                 ENDIF
>                 IF nWeight > nTopWeight
>                     nTopWeight := nWeight
>                     dDate := Today()
>                     cTime := Time24()
>                 ENDIF
>                 Sleep(100)    // give time slice to other threads for
> 1/10 second
>             END
>             IF uMsg.message != WM_QUIT .AND. !oReader:CancelRequested
>                 // Write out weight to file using file sharing
>                 IF (watchman)->(AddDbfQuiet())
>                     (watchman)->today := dDate
>                     (watchman)->time24 := cTime
>                     (watchman)->weight := nTopWeight
>                     (watchman)->scaleno := Str(pInfo.ScaleNumber,1,0)
>                     (watchman)->(DBCOMMIT())
>                     (watchman)->(DBUNLOCK())
>                 ELSE
>                     HandleError("Unable to add a record to the watchman
> file.")
>                 ENDIF
>             ELSE
>                 EXIT
>             ENDIF
>         ENDIF
>         IF uMsg.message == WM_QUIT .OR. oReader:CancelRequested
>             EXIT
>         ENDIF
>     END
>     Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Shutting down thread")
>     (watchman)->(DBCLOSEAREA())
>     RETURN 0
> FUNCTION Output( s AS STRING ) AS VOID PASCAL    // thread-safe way to
> write to log file
>     IF hDebug != NULL_PTR
>         EnterCriticalSection(@CS_DEBUG)
>         FWriteLine(hDebug, s)
>         LeaveCriticalSection(@CS_DEBUG)
>     ENDIF
>     RETURN
> FUNCTION HandleError(cError AS STRING) AS VOID PASCAL
>     LOCAL hFile AS PTR
>
>     // Thread-safe write to log file
>     EnterCriticalSection(@CS_WATCHERR)
>     IF File(GetDefault()+"watcherr.log")
>         hFile := FOpen(GetDefault()+"watcherr.log", FO_READWRITE)
>         FSeek(hFile, 0, FS_END)
>     ELSE
>         hFile := FCreate(GetDefault()+"watcherr.log")
>     ENDIF
>     IF hFile != F_ERROR
>         FWrite(hFile, DToC(Today())+" "+Time24()+"
> "+cError+_CHR(13)+_CHR(10))
>         FClose(hFile)
>     ENDIF
>     LeaveCriticalSection(@CS_WATCHERR)
> Ginny
>
> "Martin"  wrote in message news:vMgwt.107261$4C2.78184@fx23.fr7...
>
> Here we go Ginny
>
>
> Thanks
>
> Martin
>
>
> FUNCTION DelMonitor (ptrCtrl AS PTR) AS LONG STRICT
>
> LOCAL TBarList    AS bcBarList, ;
>        TBarCode    AS bcBarCode, ;
>        TOrder    AS bcOrder, ;
>        TDelList    AS bcDelList, ; //, a as csocket
>        strCtrl    AS CheckThreadControl, ;
>        pszRack    AS PSZ, ;
>        pszBat    AS PSZ, ;
>        pszProc    AS PSZ, ;
>        cOrder    AS STRING, ;
>        cCust        AS STRING, ;
>        cBarCode    AS STRING, ;
>        cProc        AS STRING, ;
>        nRack        AS DWORD, ;
>        lOk        AS LOGIC, ;
>        nCount    AS DWORD
>
> strCtrl    := ptrCtrl
> flog('a')
> IF strCtrl.lLive
>      RETURN 0
> ENDIF
> flog('b')
>
> DynLock()
> strCtrl.lLive    := TRUE
>
> //    GUI Less servers
> TBarList    := bcBarList{}
> TBarCode    := bcBarCode{}
> TOrder        := bcOrder{}
> TDelList    := bcDelList{}
>
> nCount        := 0
>
> //    big loop in here
> DO WHILE !strCtrl.lToClose
>
>      IF nCount > 3
>          EXIT
>      ENDIF
>
>      IF strCtrl.lToClose
>          EXIT
>      ENDIF
>
>      IF strCtrl.lWait
> //        pause here
>          sleep(200)
>          nCount    ++
>          LOOP
>      ENDIF
>
> //    If I have data check the batch
>      nRack    := GetpszRack(strCtrl)
>      IF nRack = 0
>          nCount    ++
>          sleep(200)
>          LOOP
>      ENDIF
>
>      DO CASE
>          CASE nRack = 1
>              pszRack    := strCtrl.pszRack1
>              pszBat    := strCtrl.pszBat1
>              pszProc    := strCtrl.pszProc1
>
>              strCtrl.pszRack1    := Null_PSZ
>          CASE nRack = 2
>              pszRack    := strCtrl.pszRack2
>              pszBat    := strCtrl.pszBat2
>              pszProc    := strCtrl.pszProc2
>
>              strCtrl.pszRack2    := Null_PSZ
>          CASE nRack = 3
>              pszRack    := strCtrl.pszRack3
>              pszBat    := strCtrl.pszBat3
>              pszProc    := strCtrl.pszProc3
>
>              strCtrl.pszRack3    := Null_PSZ
>      ENDCASE
>
>      nCount    := 0
>
>      IF TDelList:Seek(pszRack)
>          TBarCode:SetOrder(2)
>          TBarList:SetOrder(2)
>
> //        Check the order
>          cOrder    := TDelList:FieldGet(#DEL_Order)
>
>          IF TOrder:Seek(cOrder)
>              cCust    := Torder:FieldGet(#OD_CustNo)
>          ELSE
>              cCust    := 'xxxxxxxxxx'
>          ENDIF
>
>          cProc    := PSZ2String(pszProc)
>
>          lOk    := TRUE
>          DO WHILE TDellist:FieldGet(#DEL_Key) == pszBat .AND. !TDellist:EoF
>              cOrder    := TDelList:FieldGet(#DEL_Order)
>              IF TOrder:Seek(cOrder)
>
>                  IF cCust <> Torder:FieldGet(#OD_CustNo)
>                      EXIT
>                  ENDIF
>
> //                Check the barcodes
>                  TBarCode:Seek(cOrder)
>                  DO WHILE TBarCode:FieldGet(#BC_Order) == cOrder .AND.
> !TBarCode:EoF
>                      cBarcode    := TBarCode:FieldGet(#BC_Key)
>
>                      IF !TBarList:Seek(cProc+cBarcode)
>                          lOk    := FALSE
>                          EXIT
>                      ENDIF
>
>                      IF TBarList:FieldGet(#PL_Qty) <= 0
>                          lOk    := FALSE
>                          EXIT
>                      ENDIF
>
>                      TBarCode:Skip(1)
>                  ENDDO
>              ENDIF
>              TDelList:Skip(1)
>          ENDDO
>
>          IF lOk
>              PostMessage(strCtrl.hWindow,WM_APP+110,nRack,0)
>              flog('ok')
>          ELSE
>              PostMessage(strCtrl.hWindow,WM_APP+111,nRack,0)
>              flog('not')
>          ENDIF
>
>          TBarCode:SetOrder(1)
>          TBarList:SetOrder(1)
>
>       ENDIF
>
> ENDDO
>
> DynUnlock()
>
> TDelList:Close()
> TOrder:Close()
> TBarCode:Close()
> TBarList:Close()
>
> strCtrl.lLive    := FALSE
> flog('c')
>
> RETURN 0
>
>
> On 19/06/2013 12:24, Ginny Caughey wrote:
>> I don't remember seeing the VO code that runs in a worker thread then.
>> If you want to show it I may be able to make some suggestions. I had one
>> app that ran 4 worker threads accessing DBF files 24x7 for several years
>> at several sites, so it is certainly possible, but when I replaced that
>> functionality with C# apps, I used separate processes rather than
>> separate threads even though .NET has better thread handling than the VO
>> runtime.
>>
>> Ginny
>>
>> "Martin"  wrote in message news:yLdwt.151237$OL1.2491@fx13.fr7...
>>
>> Hello Ginny
>>
>> That is XBase++ code!
>>
>> See thread crashing messages for the VO Code
>>
>> Thanks
>>
>> Martin
>>
>> On 18/06/2013 17:41, Ginny Caughey wrote:
>>> I'm not sure what you mean by neatness of code, but I think you
>>> understand what I mean about threads being sort of the last choice to
>>> use. ;-)
>>>
>>> Given that this is VO, I'd try very hard to make this a separate app
>>> instead of a separate thread. The code you're showing me uses
>>> manipulates strings, for example. It looks like it wants to do something
>>> on the UI thread too, which you can't do from a worker thread. Instead
>>> you could pass a Windows message to the UI thread, which its dispatcher
>>> could interpret in some way. I'm also not seeing where you open and
>>> close the database on the worker thread. You can't manipulate the same
>>> workarea safely across threads.
>>>
>>> See my Serial class for an example of using a worker thread safely.
>>>
>>> Ginny
>>>
>>> "Martin"  wrote in message news:M9Xvt.159290$xf1.107935@fx16.fr7...
>>>
>>> Thanks Ginny
>>>
>>> The main reason is neatness of code and communications.
>>>
>>> I will be sending the rack number in a PSZ in a struct but will need to
>>> search a DBF for it.
>>>
>>> This is the code I am converting, this is in XBase++, but need it in VO
>>> 2.8. AS you can see it is not especially long, and is stable, but I
>>> can't link in huge amounts of VO into Xbase++
>>>
>>> cBat := Left(cRack,10)
>>> // Now we could monitor order or rack
>>> IF TDelList->(DBSeek(cRack))
>>> TBarCode->(OrdSetFocus(2))
>>> TBarList->(OrdSetFocus(2))
>>>
>>> // Check the order
>>> cOrder := TDelList->DEL_Order
>>> IF TOrder->(DBSeek(cOrder))
>>> cCust := Torder->OD_CustNo
>>> ELSE
>>> cCust := 'xxxxxxxxxx'
>>> ENDIF
>>>
>>> lOk := .T.
>>> DO WHILE TDellist->DEL_Key == cBat .AND. !TDellist->(EoF())
>>> cOrder := TDelList->DEL_Order
>>> IF TOrder->(DBSeek(cOrder))
>>> IF cCust <> Torder->OD_CustNo
>>> EXIT
>>> ENDIF
>>>
>>> // Check the barcodes
>>> TBarCode->(DBSeek(cOrder))
>>> DO WHILE TBarCode->BC_Order == cOrder .AND. !TBarCode->(EoF())
>>> cBarcode := TBarCode->BC_Key
>>>
>>> IF !TBarList->(DBSeek(cProc+cBarcode))
>>> lOk := .F.
>>> EXIT
>>> ENDIF
>>>
>>> IF TBarList->PL_Qty <= 0
>>> lOk := .F.
>>> EXIT
>>> ENDIF
>>>
>>> TBarCode->(DBSkip(1))
>>> ENDDO
>>> ENDIF
>>> TDelList->(DBSkip(1))
>>> ENDDO
>>>
>>> IF lOk
>>> // Fully loaded!!!!
>>> // Hit_Key('fully loaded')
>>>
>>> nPos := AT(cErr,'OPQRSTUVWXYZ')
>>> SBeep(nPos,9,'WAV')
>>> ENDIF
>>>
>>> TBarCode->(OrdSetFocus(1))
>>> TBarList->(OrdSetFocus(1))
>>> ENDIF
>>>
>>>
>>>
>>>
>>>
>>> On 18/06/2013 11:59, Ginny Caughey wrote:
>>>> If you access DBF files, don't share the workarea with any other
>>>> thread.
>>>> Use normal multiuser access patterns.
>>>> No dynamic data types such as strings that might trigger garbage
>>>> collection.
>>>> Seriously consider why this needs to be a separate thread instead of a
>>>> separate app.
>>>>
>>>> HTH,
>>>> Ginny
>>>>
>>>> "Martin"  wrote in message news:WKWvt.136194$I84.63382@fx07.fr7...
>>>>
>>>> Got quite a bit on the go now, but need a thread with data access, also
>>>> it may need to run continually.
>>>>
>>>> Anything I need to be careful with please?
>>>>
>>>> Tahnks
>>>>
>>>> Martin
>>>
>>
>

[toc] | [prev] | [next] | [standalone]


#5390

From"Ginny Caughey" <gcaughey@online.hotmail.com>
Date2013-06-20 07:22 -0400
Message-ID<51c2e5ec$0$63236$c3e8da3$3a1a2348@news.astraweb.com>
In reply to#5385
Here are the wrapper functions I'm using:

FUNCTION AddDbf()
    LOCAL dwStop AS DWORD

    WHILE TRUE
        dwStop := GetTickCountLow()+5000
        WHILE GetTickCountLow() < dwStop
               DBAPPEND()
               IF ! NetErr()
                  RETURN TRUE
               ENDIF
               Sleep(100)
        ENDDO
        IF MessageBox(0, PSZ("Unable to add a record to file"), ;
            PSZ("Append Failure"), MB_RETRYCANCEL + MB_ICONEXCLAMATION) != 
IDRETRY
            EXIT
        ENDIF
    END
    RETURN FALSE
STATIC FUNCTION ConstructUniqueAlias( cFileName AS STRING ) AS SYMBOL PASCAL
    // Borrowed from 1.0c SDK in dbfsrvr.prg
    LOCAL cTryNewAlias AS STRING
    LOCAL w AS DWORD

    IF IsNil(cFileName)
        cFileName := "NOFILENAME"
    ELSEIF ( w := At( ".", cFileName ) )>0
        cFileName := SubStr( cFileName, 1, w-1 )
    ENDIF
    w := 1
    cTryNewAlias := Upper(cFileName)

    DO WHILE VODBSymSelect( String2Symbol( cTryNewAlias ) )>0
        cTryNewAlias := Upper(cFileName)+"_"+AllTrim( Str( w++ ) )
    ENDDO

    RETURN String2Symbol(cTryNewAlias)
FUNCTION XOpenDBF(cFilename)
    RETURN OpenDbf(cFilename, , TRUE)
FUNCTION OpenDbf(cFilename, cAliasname, lExclusive)
    LOCAL dwStop AS DWORD
    LOCAL lRet AS LOGIC

    IF IsNil(lExclusive)
        lExclusive := FALSE
    ENDIF
    IF IsNil(cAliasname)
        cAliasname := cFilename
    ENDIF
    IF SELECT(cAliasname) != 0    // Alias already in use
        cAliasname := Symbol2String(ConstructUniqueAlias(cFilename))
    ENDIF
    BEGIN SEQUENCE
        WHILE TRUE
            dwStop := GetTickCountLow()+5000 // allow .5 sec. retry
            WHILE GetTickCountLow() <= dwStop
                Sleep(100)
                DBUSEAREA(TRUE, , cFilename, cAliasname, !lExclusive, FALSE)
                // use (cFilename) ALIAS (cAliasname) shared new
                IF ! NetErr()
                    lRet := TRUE
                    BREAK
                ENDIF
            END
            IF MessageBox(0, PSZ("Unable to open file "+cFilename), ;
                PSZ("File Open Error"), MB_RETRYCANCEL + MB_ICONEXCLAMATION) 
!= IDRETRY
                EXIT
            ENDIF
        ENDDO
    END SEQUENCE
    IF lRet
        cFilename := Upper(cFilename)
        DO CASE
            CASE cFilename = "RATECODE"
                DBFIELDINFO(DBS_ALIAS, FieldPos("code"), "_code")
            CASE cFilename = "TICKET"
                DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
            CASE cFilename = "INVOICE"
                DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
            CASE cFilename = "HISTORY"
                DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
        ENDCASE
    ENDIF
    RETURN lRet
FUNCTION AddDbfQuiet()
    LOCAL nTries := 0 AS INT

    EnterCriticalSection(@CS_WATCHERR)
    WHILE nTries < 10

           DBAPPEND(TRUE)
           IF !NetErr()
               LeaveCriticalSection(@CS_WATCHERR)
              RETURN TRUE
           ENDIF
           ++nTries
           Sleep(50)
    ENDDO
    LeaveCriticalSection(@CS_WATCHERR)
    RETURN FALSE
FUNCTION EditDbf()
    LOCAL nTries := 0 AS INT

    WHILE nTries < 10
        ++nTries
        //IF DBRLOCK(RECNO())
        IF DBRLOCK()
            RETURN TRUE
        ENDIF
        IF nTries < 5
            Sleep(100)
            LOOP
        ENDIF
        IF MessageBox(0, PSZ("Unable to lock record"), ;
            PSZ("Record Lock Failure"), MB_RETRYCANCEL + MB_ICONEXCLAMATION) 
!= IDRETRY
            RETURN FALSE
        ENDIF
    ENDDO
    RETURN FALSE
FUNCTION OpenDbfQuiet(cFilename, cAliasname, lExclusive)
    LOCAL nTries := 0 AS INT

    EnterCriticalSection(@CS_WATCHERR)
    IF IsNil(lExclusive)
        lExclusive := FALSE
    ENDIF
    IF IsNil(cAliasname)
        cAliasname := cFilename
    ENDIF
    IF SELECT(cAliasname) != 0    // Alias already in use
        cAliasname := Symbol2String(ConstructUniqueAlias(cFilename))
    ENDIF

    WHILE nTries < 10
        ++nTries
        DBUSEAREA(TRUE, "DBFCDX", cFilename, cAliasname, !lExclusive, FALSE)
        IF !NetErr()
            LeaveCriticalSection(@CS_WATCHERR)
            RETURN TRUE
        ENDIF
        Sleep(50)
    END
    LeaveCriticalSection(@CS_WATCHERR)
    RETURN FALSE

Ginny

"Martin"  wrote in message news:QGkwt.122934$G56.87814@fx32.fr7...

Very interesting, you are using direct DBF rather than servers, I will
try that thankyou

On 19/06/2013 15:02, Ginny Caughey wrote:
> Martin,
>
> I'm really not seeing anything obviously wrong here. Have you tried it
> without the Dynlock/Dynunlock? Here's my threaded code that ran without
> issues for several years. Maybe you'll spot something useful:
>
> FUNCTION RunPollingLoop( pInfo AS WatchInfo ) AS DWORD PASCAL    //
> Threaded function
>     LOCAL uMsg IS _winMsg    // used by thread message loop
>     LOCAL aParity AS ARRAY
>     LOCAL i AS INT
>     LOCAL cScale, cParity AS STRING
>     LOCAL nWeight, nTopWeight, nMinimumWt, nDelay AS INT
>     LOCAL dwStop AS DWORD
>     LOCAL dDate AS DATE
>     LOCAL cTime AS STRING
>     LOCAL oReader AS ScaleWatcher    // object that actually reads the
> scale and performs NTEP weight validation
>     LOCAL control, watchman, wconfig AS DWORD    // workareas for dbf 
> files
>     LOCAL lError AS LOGIC
>
>     // Update status bar with scale started text
>     PostMessage(pInfo.hWnd, MSG_StartStop, pInfo.ScaleNumber, 
> ScaleStarted)
>
>     // read paramters for this scale from wconfig and control files
>     aParity := { {"E", EvenParity}, ;
>                 {"M", MarkParity}, ;
>                 {"N", NoParity}, ;
>                 {"O", OddParity}, ;
>                 {"S", SpaceParity}     }
>
>     BEGIN SEQUENCE
>         IF !OpenDbfQuiet("control")
>             BREAK
>         ENDIF
>         control := DBGETSELECT()
>         IF !OpenDbfQuiet("wconfig")
>             BREAK
>         ENDIF
>         wconfig := DBGETSELECT()
>         IF !OpenDbfQuiet("watchman")
>             BREAK
>         ENDIF
>         watchman := DBGETSELECT()
>     RECOVER
>         lError := TRUE
>         HandleError("Unable to open a file needed to run Watchman Mode
> processing.")
>         IF control > 0
>             DBSELECTAREA(control)
>             DBCLOSEAREA()
>         ENDIF
>         IF wconfig > 0
>             DBSELECTAREA(wconfig)
>             DBCLOSEAREA()
>         ENDIF
>         IF watchman > 0
>             DBSELECTAREA(watchman)
>             DBCLOSEAREA()
>         ENDIF
>     END SEQUENCE
>
>     IF lError
>         RETURN 0
>     ENDIF
>
>     PostMessage(pInfo.hWnd, MSG_GettingData, pInfo.ScaleNumber, 0)
>     oReader := ScaleWatcher{pInfo.hWnd}
>     oReader:CommPort := "Com"+ NTrim(pInfo.PortNumber)
>     Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Getting info for 
> scale")
>
>     // Get info for this scale port from control file
>     cScale := Str(pInfo.ScaleNumber,1,0)
>     nMinimumWt := (wconfig)->minimumwt
>     nDelay := (wconfig)->interval
>     (wconfig)->(DBCLOSEAREA())
>
>     oReader:Baud := (control)->(FIELDGET(FieldPos("baud"+cScale)))
>     oReader:Databits := (control)->(FIELDGET(FieldPos("databits"+cScale)))
>     oReader:Stopbits := (control)->(FIELDGET(FieldPos("stopbits"+cScale)))
>     IF oReader:Stopbits = 1
>         oReader:Stopbits := OneStopBit    // convert to Windows value (2
> = TwoStopBits already)
>     ENDIF
>     cParity := (control)->(FIELDGET(FieldPos("parity"+cScale)))
>     i := AScan(aParity, {|aVal| aVal[1] = cParity})
>     IF i > 0
>         oReader:Parity := aParity[i,2]
>     ELSE
>         oReader:Parity := NoParity
>     ENDIF
>     oReader:Buffsize := (control)->(FIELDGET(FieldPos("buffsize"+cScale)))
>     oReader:WtBegin :=  (control)->(FIELDGET(FieldPos("wtbegin"+cScale)))
>     oReader:WtLength := (control)->(FIELDGET(FieldPos("wtlength"+cScale)))
>     oReader:CheckChar := 
> (control)->(FIELDGET(FieldPos("poll1chr"+cScale)))
>     oReader:CheckPosition :=
> (control)->(FIELDGET(FieldPos("poll2chr"+cScale)))
>     oReader:MaxRetries :=
> (control)->(FIELDGET(FieldPos("poll3chr"+cScale)))
>     oReader:MotionChar :=
> (control)->(FIELDGET(FieldPos("poll4chr"+cScale)))
>     oReader:MotionByte := (control)->(FIELDGET(FieldPos("ack"+cScale)))
>     oReader:GrossLoc := (control)->(FIELDGET(FieldPos("grossloc"+cScale)))
>     oReader:UnitLoc := (control)->(FIELDGET(FieldPos("unitloc"+cScale)))
>     oReader:ScaleUnit := (control)->(FIELDGET(FieldPos("scaleunit")))
>     (control)->(DBCLOSEAREA())
>
>     // Run polling loop until WM_QUIT received from primary thread
>     // Polling is a two step process here:
>     //    1. Sample every nDelay seconds for a weigh large enough to
> indicate a vehicle
>     //    2. Once a vehicle is on the scale, sample at 1/10 second
> intervals to catch maximum weight
>     WHILE TRUE
>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - In polling loop")
>         //PostMessage(pInfo.hWnd, MSG_Polling, pInfo.ScaleNumber, 0)
>         IF PeekMessage(@uMsg, 0, 0, 0, PM_REMOVE)    // PeekMessage
> returns true if any messages in queue
>             IF uMsg.message == WM_QUIT
>                 EXIT
>             ENDIF
>         ENDIF
>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Getting first
> weight")
>         nWeight := oReader:ReadScale()
>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - nWeight is
> "+NTrim(nWeight))
>         IF oReader:CancelRequested
>             EXIT
>         ENDIF
>         IF nWeight = -1    // Error occurred
>             PostMessage(pInfo.hWnd, MSG_ScaleError, pInfo.ScaleNumber, 0)
>         ELSEIF nWeight < nMinimumWt
>             dwStop := GetTickCountLow()+DWORD(nDelay * 1000)
>             //PostMessage(pInfo.hWnd, MSG_Polling, pInfo.ScaleNumber, 0)
>             WHILE GetTickCountLow() <= dwStop
>                 IF PeekMessage(@uMsg, 0, 0, 0, PM_REMOVE)
>                     IF uMsg.message == WM_QUIT
>                         EXIT
>                     ENDIF
>                 ENDIF
>             END
>         ELSE
>             // We have a vehicle on scale
>             // Sample every 1/10 second until its maximum weight is
> captured
>             PostMessage(pInfo.hWnd, MSG_Sampling, pInfo.ScaleNumber, 0)
>             nTopWeight := nWeight
>             dDate := Today()
>             cTime := Time24()
>             WHILE TRUE
>                 IF PeekMessage(@uMsg, 0, 0, 0, PM_NOREMOVE)
>                     IF uMsg.message == WM_QUIT
>                         EXIT
>                     ENDIF
>                 ENDIF
>                 Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Testing
> for maximum weight")
>                 nWeight := oReader:ReadScale()
>                 IF oReader:CancelRequested
>                     EXIT
>                 ENDIF
>                 IF nWeight < nMinimumWt .AND. !oReader:MotionDetected
>                     EXIT
>                 ENDIF
>                 IF nWeight > nTopWeight
>                     nTopWeight := nWeight
>                     dDate := Today()
>                     cTime := Time24()
>                 ENDIF
>                 Sleep(100)    // give time slice to other threads for
> 1/10 second
>             END
>             IF uMsg.message != WM_QUIT .AND. !oReader:CancelRequested
>                 // Write out weight to file using file sharing
>                 IF (watchman)->(AddDbfQuiet())
>                     (watchman)->today := dDate
>                     (watchman)->time24 := cTime
>                     (watchman)->weight := nTopWeight
>                     (watchman)->scaleno := Str(pInfo.ScaleNumber,1,0)
>                     (watchman)->(DBCOMMIT())
>                     (watchman)->(DBUNLOCK())
>                 ELSE
>                     HandleError("Unable to add a record to the watchman
> file.")
>                 ENDIF
>             ELSE
>                 EXIT
>             ENDIF
>         ENDIF
>         IF uMsg.message == WM_QUIT .OR. oReader:CancelRequested
>             EXIT
>         ENDIF
>     END
>     Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Shutting down thread")
>     (watchman)->(DBCLOSEAREA())
>     RETURN 0
> FUNCTION Output( s AS STRING ) AS VOID PASCAL    // thread-safe way to
> write to log file
>     IF hDebug != NULL_PTR
>         EnterCriticalSection(@CS_DEBUG)
>         FWriteLine(hDebug, s)
>         LeaveCriticalSection(@CS_DEBUG)
>     ENDIF
>     RETURN
> FUNCTION HandleError(cError AS STRING) AS VOID PASCAL
>     LOCAL hFile AS PTR
>
>     // Thread-safe write to log file
>     EnterCriticalSection(@CS_WATCHERR)
>     IF File(GetDefault()+"watcherr.log")
>         hFile := FOpen(GetDefault()+"watcherr.log", FO_READWRITE)
>         FSeek(hFile, 0, FS_END)
>     ELSE
>         hFile := FCreate(GetDefault()+"watcherr.log")
>     ENDIF
>     IF hFile != F_ERROR
>         FWrite(hFile, DToC(Today())+" "+Time24()+"
> "+cError+_CHR(13)+_CHR(10))
>         FClose(hFile)
>     ENDIF
>     LeaveCriticalSection(@CS_WATCHERR)
> Ginny
>
> "Martin"  wrote in message news:vMgwt.107261$4C2.78184@fx23.fr7...
>
> Here we go Ginny
>
>
> Thanks
>
> Martin
>
>
> FUNCTION DelMonitor (ptrCtrl AS PTR) AS LONG STRICT
>
> LOCAL TBarList    AS bcBarList, ;
>        TBarCode    AS bcBarCode, ;
>        TOrder    AS bcOrder, ;
>        TDelList    AS bcDelList, ; //, a as csocket
>        strCtrl    AS CheckThreadControl, ;
>        pszRack    AS PSZ, ;
>        pszBat    AS PSZ, ;
>        pszProc    AS PSZ, ;
>        cOrder    AS STRING, ;
>        cCust        AS STRING, ;
>        cBarCode    AS STRING, ;
>        cProc        AS STRING, ;
>        nRack        AS DWORD, ;
>        lOk        AS LOGIC, ;
>        nCount    AS DWORD
>
> strCtrl    := ptrCtrl
> flog('a')
> IF strCtrl.lLive
>      RETURN 0
> ENDIF
> flog('b')
>
> DynLock()
> strCtrl.lLive    := TRUE
>
> //    GUI Less servers
> TBarList    := bcBarList{}
> TBarCode    := bcBarCode{}
> TOrder        := bcOrder{}
> TDelList    := bcDelList{}
>
> nCount        := 0
>
> //    big loop in here
> DO WHILE !strCtrl.lToClose
>
>      IF nCount > 3
>          EXIT
>      ENDIF
>
>      IF strCtrl.lToClose
>          EXIT
>      ENDIF
>
>      IF strCtrl.lWait
> //        pause here
>          sleep(200)
>          nCount    ++
>          LOOP
>      ENDIF
>
> //    If I have data check the batch
>      nRack    := GetpszRack(strCtrl)
>      IF nRack = 0
>          nCount    ++
>          sleep(200)
>          LOOP
>      ENDIF
>
>      DO CASE
>          CASE nRack = 1
>              pszRack    := strCtrl.pszRack1
>              pszBat    := strCtrl.pszBat1
>              pszProc    := strCtrl.pszProc1
>
>              strCtrl.pszRack1    := Null_PSZ
>          CASE nRack = 2
>              pszRack    := strCtrl.pszRack2
>              pszBat    := strCtrl.pszBat2
>              pszProc    := strCtrl.pszProc2
>
>              strCtrl.pszRack2    := Null_PSZ
>          CASE nRack = 3
>              pszRack    := strCtrl.pszRack3
>              pszBat    := strCtrl.pszBat3
>              pszProc    := strCtrl.pszProc3
>
>              strCtrl.pszRack3    := Null_PSZ
>      ENDCASE
>
>      nCount    := 0
>
>      IF TDelList:Seek(pszRack)
>          TBarCode:SetOrder(2)
>          TBarList:SetOrder(2)
>
> //        Check the order
>          cOrder    := TDelList:FieldGet(#DEL_Order)
>
>          IF TOrder:Seek(cOrder)
>              cCust    := Torder:FieldGet(#OD_CustNo)
>          ELSE
>              cCust    := 'xxxxxxxxxx'
>          ENDIF
>
>          cProc    := PSZ2String(pszProc)
>
>          lOk    := TRUE
>          DO WHILE TDellist:FieldGet(#DEL_Key) == pszBat .AND. 
> !TDellist:EoF
>              cOrder    := TDelList:FieldGet(#DEL_Order)
>              IF TOrder:Seek(cOrder)
>
>                  IF cCust <> Torder:FieldGet(#OD_CustNo)
>                      EXIT
>                  ENDIF
>
> //                Check the barcodes
>                  TBarCode:Seek(cOrder)
>                  DO WHILE TBarCode:FieldGet(#BC_Order) == cOrder .AND.
> !TBarCode:EoF
>                      cBarcode    := TBarCode:FieldGet(#BC_Key)
>
>                      IF !TBarList:Seek(cProc+cBarcode)
>                          lOk    := FALSE
>                          EXIT
>                      ENDIF
>
>                      IF TBarList:FieldGet(#PL_Qty) <= 0
>                          lOk    := FALSE
>                          EXIT
>                      ENDIF
>
>                      TBarCode:Skip(1)
>                  ENDDO
>              ENDIF
>              TDelList:Skip(1)
>          ENDDO
>
>          IF lOk
>              PostMessage(strCtrl.hWindow,WM_APP+110,nRack,0)
>              flog('ok')
>          ELSE
>              PostMessage(strCtrl.hWindow,WM_APP+111,nRack,0)
>              flog('not')
>          ENDIF
>
>          TBarCode:SetOrder(1)
>          TBarList:SetOrder(1)
>
>       ENDIF
>
> ENDDO
>
> DynUnlock()
>
> TDelList:Close()
> TOrder:Close()
> TBarCode:Close()
> TBarList:Close()
>
> strCtrl.lLive    := FALSE
> flog('c')
>
> RETURN 0
>
>
> On 19/06/2013 12:24, Ginny Caughey wrote:
>> I don't remember seeing the VO code that runs in a worker thread then.
>> If you want to show it I may be able to make some suggestions. I had one
>> app that ran 4 worker threads accessing DBF files 24x7 for several years
>> at several sites, so it is certainly possible, but when I replaced that
>> functionality with C# apps, I used separate processes rather than
>> separate threads even though .NET has better thread handling than the VO
>> runtime.
>>
>> Ginny
>>
>> "Martin"  wrote in message news:yLdwt.151237$OL1.2491@fx13.fr7...
>>
>> Hello Ginny
>>
>> That is XBase++ code!
>>
>> See thread crashing messages for the VO Code
>>
>> Thanks
>>
>> Martin
>>
>> On 18/06/2013 17:41, Ginny Caughey wrote:
>>> I'm not sure what you mean by neatness of code, but I think you
>>> understand what I mean about threads being sort of the last choice to
>>> use. ;-)
>>>
>>> Given that this is VO, I'd try very hard to make this a separate app
>>> instead of a separate thread. The code you're showing me uses
>>> manipulates strings, for example. It looks like it wants to do something
>>> on the UI thread too, which you can't do from a worker thread. Instead
>>> you could pass a Windows message to the UI thread, which its dispatcher
>>> could interpret in some way. I'm also not seeing where you open and
>>> close the database on the worker thread. You can't manipulate the same
>>> workarea safely across threads.
>>>
>>> See my Serial class for an example of using a worker thread safely.
>>>
>>> Ginny
>>>
>>> "Martin"  wrote in message news:M9Xvt.159290$xf1.107935@fx16.fr7...
>>>
>>> Thanks Ginny
>>>
>>> The main reason is neatness of code and communications.
>>>
>>> I will be sending the rack number in a PSZ in a struct but will need to
>>> search a DBF for it.
>>>
>>> This is the code I am converting, this is in XBase++, but need it in VO
>>> 2.8. AS you can see it is not especially long, and is stable, but I
>>> can't link in huge amounts of VO into Xbase++
>>>
>>> cBat := Left(cRack,10)
>>> // Now we could monitor order or rack
>>> IF TDelList->(DBSeek(cRack))
>>> TBarCode->(OrdSetFocus(2))
>>> TBarList->(OrdSetFocus(2))
>>>
>>> // Check the order
>>> cOrder := TDelList->DEL_Order
>>> IF TOrder->(DBSeek(cOrder))
>>> cCust := Torder->OD_CustNo
>>> ELSE
>>> cCust := 'xxxxxxxxxx'
>>> ENDIF
>>>
>>> lOk := .T.
>>> DO WHILE TDellist->DEL_Key == cBat .AND. !TDellist->(EoF())
>>> cOrder := TDelList->DEL_Order
>>> IF TOrder->(DBSeek(cOrder))
>>> IF cCust <> Torder->OD_CustNo
>>> EXIT
>>> ENDIF
>>>
>>> // Check the barcodes
>>> TBarCode->(DBSeek(cOrder))
>>> DO WHILE TBarCode->BC_Order == cOrder .AND. !TBarCode->(EoF())
>>> cBarcode := TBarCode->BC_Key
>>>
>>> IF !TBarList->(DBSeek(cProc+cBarcode))
>>> lOk := .F.
>>> EXIT
>>> ENDIF
>>>
>>> IF TBarList->PL_Qty <= 0
>>> lOk := .F.
>>> EXIT
>>> ENDIF
>>>
>>> TBarCode->(DBSkip(1))
>>> ENDDO
>>> ENDIF
>>> TDelList->(DBSkip(1))
>>> ENDDO
>>>
>>> IF lOk
>>> // Fully loaded!!!!
>>> // Hit_Key('fully loaded')
>>>
>>> nPos := AT(cErr,'OPQRSTUVWXYZ')
>>> SBeep(nPos,9,'WAV')
>>> ENDIF
>>>
>>> TBarCode->(OrdSetFocus(1))
>>> TBarList->(OrdSetFocus(1))
>>> ENDIF
>>>
>>>
>>>
>>>
>>>
>>> On 18/06/2013 11:59, Ginny Caughey wrote:
>>>> If you access DBF files, don't share the workarea with any other
>>>> thread.
>>>> Use normal multiuser access patterns.
>>>> No dynamic data types such as strings that might trigger garbage
>>>> collection.
>>>> Seriously consider why this needs to be a separate thread instead of a
>>>> separate app.
>>>>
>>>> HTH,
>>>> Ginny
>>>>
>>>> "Martin"  wrote in message news:WKWvt.136194$I84.63382@fx07.fr7...
>>>>
>>>> Got quite a bit on the go now, but need a thread with data access, also
>>>> it may need to run continually.
>>>>
>>>> Anything I need to be careful with please?
>>>>
>>>> Tahnks
>>>>
>>>> Martin
>>>
>>
> 

[toc] | [prev] | [next] | [standalone]


#5391

FromMartin <spam@spam.spam>
Date2013-06-20 17:12 +0100
Message-ID<ARFwt.114422$P_4.83439@fx31.fr7>
In reply to#5390
Thanks Ginny

Just been testing since we have got the server running (blew up after 
power cut despite UPS), with thread running the scanning code (main 
.exe) crashes accessing the barcode system. thread carries on running 
until I quit.

Not using servers in thread, but Clipper style, any access controlled 
with critical sections

Note the same type of error in two files, both are open in the thread 
with their own opens.

Arg:             uField
ArgNum:          0
Args:          1 BC_ORDER : SYMBOL
ArgType:         NIL
ArgTypeReq:      NIL
CallFuncSym:     FIELDGET
CanDefault:      .F.
CanRetry:        .F.
CanSubstitute:   .F.
Description:     Wrong field specification



Error Detail
Arg:             uField
ArgNum:          0
Args:          1 PL_DATE : SYMBOL
ArgType:         NIL
ArgTypeReq:      NIL
CallFuncSym:     FIELDGET
CanDefault:      .F.
CanRetry:        .F.
CanSubstitute:   .F.
Description:     Wrong field specification
FileHandle:      0
FileName:
FuncPtr:         0x00000000
FuncSym:         FIELDGET
GenCode:         1 : Argument error
MaxSize:         0
MethodSelf:      BarList
Operation:
OsCode:          0 : Successful completion
Severity:        ERROR
SubCode:         0
SubCodeText:
SubstituteType:  NIL
SubSystem:       Database
Tries:           0




On 20/06/2013 12:22, Ginny Caughey wrote:
> Here are the wrapper functions I'm using:
>
> FUNCTION AddDbf()
>     LOCAL dwStop AS DWORD
>
>     WHILE TRUE
>         dwStop := GetTickCountLow()+5000
>         WHILE GetTickCountLow() < dwStop
>                DBAPPEND()
>                IF ! NetErr()
>                   RETURN TRUE
>                ENDIF
>                Sleep(100)
>         ENDDO
>         IF MessageBox(0, PSZ("Unable to add a record to file"), ;
>             PSZ("Append Failure"), MB_RETRYCANCEL + MB_ICONEXCLAMATION)
> != IDRETRY
>             EXIT
>         ENDIF
>     END
>     RETURN FALSE
> STATIC FUNCTION ConstructUniqueAlias( cFileName AS STRING ) AS SYMBOL
> PASCAL
>     // Borrowed from 1.0c SDK in dbfsrvr.prg
>     LOCAL cTryNewAlias AS STRING
>     LOCAL w AS DWORD
>
>     IF IsNil(cFileName)
>         cFileName := "NOFILENAME"
>     ELSEIF ( w := At( ".", cFileName ) )>0
>         cFileName := SubStr( cFileName, 1, w-1 )
>     ENDIF
>     w := 1
>     cTryNewAlias := Upper(cFileName)
>
>     DO WHILE VODBSymSelect( String2Symbol( cTryNewAlias ) )>0
>         cTryNewAlias := Upper(cFileName)+"_"+AllTrim( Str( w++ ) )
>     ENDDO
>
>     RETURN String2Symbol(cTryNewAlias)
> FUNCTION XOpenDBF(cFilename)
>     RETURN OpenDbf(cFilename, , TRUE)
> FUNCTION OpenDbf(cFilename, cAliasname, lExclusive)
>     LOCAL dwStop AS DWORD
>     LOCAL lRet AS LOGIC
>
>     IF IsNil(lExclusive)
>         lExclusive := FALSE
>     ENDIF
>     IF IsNil(cAliasname)
>         cAliasname := cFilename
>     ENDIF
>     IF SELECT(cAliasname) != 0    // Alias already in use
>         cAliasname := Symbol2String(ConstructUniqueAlias(cFilename))
>     ENDIF
>     BEGIN SEQUENCE
>         WHILE TRUE
>             dwStop := GetTickCountLow()+5000 // allow .5 sec. retry
>             WHILE GetTickCountLow() <= dwStop
>                 Sleep(100)
>                 DBUSEAREA(TRUE, , cFilename, cAliasname, !lExclusive,
> FALSE)
>                 // use (cFilename) ALIAS (cAliasname) shared new
>                 IF ! NetErr()
>                     lRet := TRUE
>                     BREAK
>                 ENDIF
>             END
>             IF MessageBox(0, PSZ("Unable to open file "+cFilename), ;
>                 PSZ("File Open Error"), MB_RETRYCANCEL +
> MB_ICONEXCLAMATION) != IDRETRY
>                 EXIT
>             ENDIF
>         ENDDO
>     END SEQUENCE
>     IF lRet
>         cFilename := Upper(cFilename)
>         DO CASE
>             CASE cFilename = "RATECODE"
>                 DBFIELDINFO(DBS_ALIAS, FieldPos("code"), "_code")
>             CASE cFilename = "TICKET"
>                 DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
>             CASE cFilename = "INVOICE"
>                 DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
>             CASE cFilename = "HISTORY"
>                 DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
>         ENDCASE
>     ENDIF
>     RETURN lRet
> FUNCTION AddDbfQuiet()
>     LOCAL nTries := 0 AS INT
>
>     EnterCriticalSection(@CS_WATCHERR)
>     WHILE nTries < 10
>
>            DBAPPEND(TRUE)
>            IF !NetErr()
>                LeaveCriticalSection(@CS_WATCHERR)
>               RETURN TRUE
>            ENDIF
>            ++nTries
>            Sleep(50)
>     ENDDO
>     LeaveCriticalSection(@CS_WATCHERR)
>     RETURN FALSE
> FUNCTION EditDbf()
>     LOCAL nTries := 0 AS INT
>
>     WHILE nTries < 10
>         ++nTries
>         //IF DBRLOCK(RECNO())
>         IF DBRLOCK()
>             RETURN TRUE
>         ENDIF
>         IF nTries < 5
>             Sleep(100)
>             LOOP
>         ENDIF
>         IF MessageBox(0, PSZ("Unable to lock record"), ;
>             PSZ("Record Lock Failure"), MB_RETRYCANCEL +
> MB_ICONEXCLAMATION) != IDRETRY
>             RETURN FALSE
>         ENDIF
>     ENDDO
>     RETURN FALSE
> FUNCTION OpenDbfQuiet(cFilename, cAliasname, lExclusive)
>     LOCAL nTries := 0 AS INT
>
>     EnterCriticalSection(@CS_WATCHERR)
>     IF IsNil(lExclusive)
>         lExclusive := FALSE
>     ENDIF
>     IF IsNil(cAliasname)
>         cAliasname := cFilename
>     ENDIF
>     IF SELECT(cAliasname) != 0    // Alias already in use
>         cAliasname := Symbol2String(ConstructUniqueAlias(cFilename))
>     ENDIF
>
>     WHILE nTries < 10
>         ++nTries
>         DBUSEAREA(TRUE, "DBFCDX", cFilename, cAliasname, !lExclusive,
> FALSE)
>         IF !NetErr()
>             LeaveCriticalSection(@CS_WATCHERR)
>             RETURN TRUE
>         ENDIF
>         Sleep(50)
>     END
>     LeaveCriticalSection(@CS_WATCHERR)
>     RETURN FALSE
>
> Ginny
>
> "Martin"  wrote in message news:QGkwt.122934$G56.87814@fx32.fr7...
>
> Very interesting, you are using direct DBF rather than servers, I will
> try that thankyou
>
> On 19/06/2013 15:02, Ginny Caughey wrote:
>> Martin,
>>
>> I'm really not seeing anything obviously wrong here. Have you tried it
>> without the Dynlock/Dynunlock? Here's my threaded code that ran without
>> issues for several years. Maybe you'll spot something useful:
>>
>> FUNCTION RunPollingLoop( pInfo AS WatchInfo ) AS DWORD PASCAL    //
>> Threaded function
>>     LOCAL uMsg IS _winMsg    // used by thread message loop
>>     LOCAL aParity AS ARRAY
>>     LOCAL i AS INT
>>     LOCAL cScale, cParity AS STRING
>>     LOCAL nWeight, nTopWeight, nMinimumWt, nDelay AS INT
>>     LOCAL dwStop AS DWORD
>>     LOCAL dDate AS DATE
>>     LOCAL cTime AS STRING
>>     LOCAL oReader AS ScaleWatcher    // object that actually reads the
>> scale and performs NTEP weight validation
>>     LOCAL control, watchman, wconfig AS DWORD    // workareas for dbf
>> files
>>     LOCAL lError AS LOGIC
>>
>>     // Update status bar with scale started text
>>     PostMessage(pInfo.hWnd, MSG_StartStop, pInfo.ScaleNumber,
>> ScaleStarted)
>>
>>     // read paramters for this scale from wconfig and control files
>>     aParity := { {"E", EvenParity}, ;
>>                 {"M", MarkParity}, ;
>>                 {"N", NoParity}, ;
>>                 {"O", OddParity}, ;
>>                 {"S", SpaceParity}     }
>>
>>     BEGIN SEQUENCE
>>         IF !OpenDbfQuiet("control")
>>             BREAK
>>         ENDIF
>>         control := DBGETSELECT()
>>         IF !OpenDbfQuiet("wconfig")
>>             BREAK
>>         ENDIF
>>         wconfig := DBGETSELECT()
>>         IF !OpenDbfQuiet("watchman")
>>             BREAK
>>         ENDIF
>>         watchman := DBGETSELECT()
>>     RECOVER
>>         lError := TRUE
>>         HandleError("Unable to open a file needed to run Watchman Mode
>> processing.")
>>         IF control > 0
>>             DBSELECTAREA(control)
>>             DBCLOSEAREA()
>>         ENDIF
>>         IF wconfig > 0
>>             DBSELECTAREA(wconfig)
>>             DBCLOSEAREA()
>>         ENDIF
>>         IF watchman > 0
>>             DBSELECTAREA(watchman)
>>             DBCLOSEAREA()
>>         ENDIF
>>     END SEQUENCE
>>
>>     IF lError
>>         RETURN 0
>>     ENDIF
>>
>>     PostMessage(pInfo.hWnd, MSG_GettingData, pInfo.ScaleNumber, 0)
>>     oReader := ScaleWatcher{pInfo.hWnd}
>>     oReader:CommPort := "Com"+ NTrim(pInfo.PortNumber)
>>     Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Getting info for
>> scale")
>>
>>     // Get info for this scale port from control file
>>     cScale := Str(pInfo.ScaleNumber,1,0)
>>     nMinimumWt := (wconfig)->minimumwt
>>     nDelay := (wconfig)->interval
>>     (wconfig)->(DBCLOSEAREA())
>>
>>     oReader:Baud := (control)->(FIELDGET(FieldPos("baud"+cScale)))
>>     oReader:Databits :=
>> (control)->(FIELDGET(FieldPos("databits"+cScale)))
>>     oReader:Stopbits :=
>> (control)->(FIELDGET(FieldPos("stopbits"+cScale)))
>>     IF oReader:Stopbits = 1
>>         oReader:Stopbits := OneStopBit    // convert to Windows value (2
>> = TwoStopBits already)
>>     ENDIF
>>     cParity := (control)->(FIELDGET(FieldPos("parity"+cScale)))
>>     i := AScan(aParity, {|aVal| aVal[1] = cParity})
>>     IF i > 0
>>         oReader:Parity := aParity[i,2]
>>     ELSE
>>         oReader:Parity := NoParity
>>     ENDIF
>>     oReader:Buffsize :=
>> (control)->(FIELDGET(FieldPos("buffsize"+cScale)))
>>     oReader:WtBegin :=  (control)->(FIELDGET(FieldPos("wtbegin"+cScale)))
>>     oReader:WtLength :=
>> (control)->(FIELDGET(FieldPos("wtlength"+cScale)))
>>     oReader:CheckChar :=
>> (control)->(FIELDGET(FieldPos("poll1chr"+cScale)))
>>     oReader:CheckPosition :=
>> (control)->(FIELDGET(FieldPos("poll2chr"+cScale)))
>>     oReader:MaxRetries :=
>> (control)->(FIELDGET(FieldPos("poll3chr"+cScale)))
>>     oReader:MotionChar :=
>> (control)->(FIELDGET(FieldPos("poll4chr"+cScale)))
>>     oReader:MotionByte := (control)->(FIELDGET(FieldPos("ack"+cScale)))
>>     oReader:GrossLoc :=
>> (control)->(FIELDGET(FieldPos("grossloc"+cScale)))
>>     oReader:UnitLoc := (control)->(FIELDGET(FieldPos("unitloc"+cScale)))
>>     oReader:ScaleUnit := (control)->(FIELDGET(FieldPos("scaleunit")))
>>     (control)->(DBCLOSEAREA())
>>
>>     // Run polling loop until WM_QUIT received from primary thread
>>     // Polling is a two step process here:
>>     //    1. Sample every nDelay seconds for a weigh large enough to
>> indicate a vehicle
>>     //    2. Once a vehicle is on the scale, sample at 1/10 second
>> intervals to catch maximum weight
>>     WHILE TRUE
>>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - In polling loop")
>>         //PostMessage(pInfo.hWnd, MSG_Polling, pInfo.ScaleNumber, 0)
>>         IF PeekMessage(@uMsg, 0, 0, 0, PM_REMOVE)    // PeekMessage
>> returns true if any messages in queue
>>             IF uMsg.message == WM_QUIT
>>                 EXIT
>>             ENDIF
>>         ENDIF
>>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Getting first
>> weight")
>>         nWeight := oReader:ReadScale()
>>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - nWeight is
>> "+NTrim(nWeight))
>>         IF oReader:CancelRequested
>>             EXIT
>>         ENDIF
>>         IF nWeight = -1    // Error occurred
>>             PostMessage(pInfo.hWnd, MSG_ScaleError, pInfo.ScaleNumber, 0)
>>         ELSEIF nWeight < nMinimumWt
>>             dwStop := GetTickCountLow()+DWORD(nDelay * 1000)
>>             //PostMessage(pInfo.hWnd, MSG_Polling, pInfo.ScaleNumber, 0)
>>             WHILE GetTickCountLow() <= dwStop
>>                 IF PeekMessage(@uMsg, 0, 0, 0, PM_REMOVE)
>>                     IF uMsg.message == WM_QUIT
>>                         EXIT
>>                     ENDIF
>>                 ENDIF
>>             END
>>         ELSE
>>             // We have a vehicle on scale
>>             // Sample every 1/10 second until its maximum weight is
>> captured
>>             PostMessage(pInfo.hWnd, MSG_Sampling, pInfo.ScaleNumber, 0)
>>             nTopWeight := nWeight
>>             dDate := Today()
>>             cTime := Time24()
>>             WHILE TRUE
>>                 IF PeekMessage(@uMsg, 0, 0, 0, PM_NOREMOVE)
>>                     IF uMsg.message == WM_QUIT
>>                         EXIT
>>                     ENDIF
>>                 ENDIF
>>                 Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Testing
>> for maximum weight")
>>                 nWeight := oReader:ReadScale()
>>                 IF oReader:CancelRequested
>>                     EXIT
>>                 ENDIF
>>                 IF nWeight < nMinimumWt .AND. !oReader:MotionDetected
>>                     EXIT
>>                 ENDIF
>>                 IF nWeight > nTopWeight
>>                     nTopWeight := nWeight
>>                     dDate := Today()
>>                     cTime := Time24()
>>                 ENDIF
>>                 Sleep(100)    // give time slice to other threads for
>> 1/10 second
>>             END
>>             IF uMsg.message != WM_QUIT .AND. !oReader:CancelRequested
>>                 // Write out weight to file using file sharing
>>                 IF (watchman)->(AddDbfQuiet())
>>                     (watchman)->today := dDate
>>                     (watchman)->time24 := cTime
>>                     (watchman)->weight := nTopWeight
>>                     (watchman)->scaleno := Str(pInfo.ScaleNumber,1,0)
>>                     (watchman)->(DBCOMMIT())
>>                     (watchman)->(DBUNLOCK())
>>                 ELSE
>>                     HandleError("Unable to add a record to the watchman
>> file.")
>>                 ENDIF
>>             ELSE
>>                 EXIT
>>             ENDIF
>>         ENDIF
>>         IF uMsg.message == WM_QUIT .OR. oReader:CancelRequested
>>             EXIT
>>         ENDIF
>>     END
>>     Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Shutting down thread")
>>     (watchman)->(DBCLOSEAREA())
>>     RETURN 0
>> FUNCTION Output( s AS STRING ) AS VOID PASCAL    // thread-safe way to
>> write to log file
>>     IF hDebug != NULL_PTR
>>         EnterCriticalSection(@CS_DEBUG)
>>         FWriteLine(hDebug, s)
>>         LeaveCriticalSection(@CS_DEBUG)
>>     ENDIF
>>     RETURN
>> FUNCTION HandleError(cError AS STRING) AS VOID PASCAL
>>     LOCAL hFile AS PTR
>>
>>     // Thread-safe write to log file
>>     EnterCriticalSection(@CS_WATCHERR)
>>     IF File(GetDefault()+"watcherr.log")
>>         hFile := FOpen(GetDefault()+"watcherr.log", FO_READWRITE)
>>         FSeek(hFile, 0, FS_END)
>>     ELSE
>>         hFile := FCreate(GetDefault()+"watcherr.log")
>>     ENDIF
>>     IF hFile != F_ERROR
>>         FWrite(hFile, DToC(Today())+" "+Time24()+"
>> "+cError+_CHR(13)+_CHR(10))
>>         FClose(hFile)
>>     ENDIF
>>     LeaveCriticalSection(@CS_WATCHERR)
>> Ginny
>>
>> "Martin"  wrote in message news:vMgwt.107261$4C2.78184@fx23.fr7...
>>
>> Here we go Ginny
>>
>>
>> Thanks
>>
>> Martin
>>

[toc] | [prev] | [next] | [standalone]


#5392

From"Ginny Caughey" <gcaughey@online.hotmail.com>
Date2013-06-20 14:04 -0400
Message-ID<51c34422$0$57923$c3e8da3$eb767761@news.astraweb.com>
In reply to#5391
If your UI thread is accessing DBF files without using the same DBF 
functions as the worker thread, that could be the issue.

Ginny

"Martin"  wrote in message news:ARFwt.114422$P_4.83439@fx31.fr7...

Thanks Ginny

Just been testing since we have got the server running (blew up after
power cut despite UPS), with thread running the scanning code (main
.exe) crashes accessing the barcode system. thread carries on running
until I quit.

Not using servers in thread, but Clipper style, any access controlled
with critical sections

Note the same type of error in two files, both are open in the thread
with their own opens.

Arg:             uField
ArgNum:          0
Args:          1 BC_ORDER : SYMBOL
ArgType:         NIL
ArgTypeReq:      NIL
CallFuncSym:     FIELDGET
CanDefault:      .F.
CanRetry:        .F.
CanSubstitute:   .F.
Description:     Wrong field specification



Error Detail
Arg:             uField
ArgNum:          0
Args:          1 PL_DATE : SYMBOL
ArgType:         NIL
ArgTypeReq:      NIL
CallFuncSym:     FIELDGET
CanDefault:      .F.
CanRetry:        .F.
CanSubstitute:   .F.
Description:     Wrong field specification
FileHandle:      0
FileName:
FuncPtr:         0x00000000
FuncSym:         FIELDGET
GenCode:         1 : Argument error
MaxSize:         0
MethodSelf:      BarList
Operation:
OsCode:          0 : Successful completion
Severity:        ERROR
SubCode:         0
SubCodeText:
SubstituteType:  NIL
SubSystem:       Database
Tries:           0




On 20/06/2013 12:22, Ginny Caughey wrote:
> Here are the wrapper functions I'm using:
>
> FUNCTION AddDbf()
>     LOCAL dwStop AS DWORD
>
>     WHILE TRUE
>         dwStop := GetTickCountLow()+5000
>         WHILE GetTickCountLow() < dwStop
>                DBAPPEND()
>                IF ! NetErr()
>                   RETURN TRUE
>                ENDIF
>                Sleep(100)
>         ENDDO
>         IF MessageBox(0, PSZ("Unable to add a record to file"), ;
>             PSZ("Append Failure"), MB_RETRYCANCEL + MB_ICONEXCLAMATION)
> != IDRETRY
>             EXIT
>         ENDIF
>     END
>     RETURN FALSE
> STATIC FUNCTION ConstructUniqueAlias( cFileName AS STRING ) AS SYMBOL
> PASCAL
>     // Borrowed from 1.0c SDK in dbfsrvr.prg
>     LOCAL cTryNewAlias AS STRING
>     LOCAL w AS DWORD
>
>     IF IsNil(cFileName)
>         cFileName := "NOFILENAME"
>     ELSEIF ( w := At( ".", cFileName ) )>0
>         cFileName := SubStr( cFileName, 1, w-1 )
>     ENDIF
>     w := 1
>     cTryNewAlias := Upper(cFileName)
>
>     DO WHILE VODBSymSelect( String2Symbol( cTryNewAlias ) )>0
>         cTryNewAlias := Upper(cFileName)+"_"+AllTrim( Str( w++ ) )
>     ENDDO
>
>     RETURN String2Symbol(cTryNewAlias)
> FUNCTION XOpenDBF(cFilename)
>     RETURN OpenDbf(cFilename, , TRUE)
> FUNCTION OpenDbf(cFilename, cAliasname, lExclusive)
>     LOCAL dwStop AS DWORD
>     LOCAL lRet AS LOGIC
>
>     IF IsNil(lExclusive)
>         lExclusive := FALSE
>     ENDIF
>     IF IsNil(cAliasname)
>         cAliasname := cFilename
>     ENDIF
>     IF SELECT(cAliasname) != 0    // Alias already in use
>         cAliasname := Symbol2String(ConstructUniqueAlias(cFilename))
>     ENDIF
>     BEGIN SEQUENCE
>         WHILE TRUE
>             dwStop := GetTickCountLow()+5000 // allow .5 sec. retry
>             WHILE GetTickCountLow() <= dwStop
>                 Sleep(100)
>                 DBUSEAREA(TRUE, , cFilename, cAliasname, !lExclusive,
> FALSE)
>                 // use (cFilename) ALIAS (cAliasname) shared new
>                 IF ! NetErr()
>                     lRet := TRUE
>                     BREAK
>                 ENDIF
>             END
>             IF MessageBox(0, PSZ("Unable to open file "+cFilename), ;
>                 PSZ("File Open Error"), MB_RETRYCANCEL +
> MB_ICONEXCLAMATION) != IDRETRY
>                 EXIT
>             ENDIF
>         ENDDO
>     END SEQUENCE
>     IF lRet
>         cFilename := Upper(cFilename)
>         DO CASE
>             CASE cFilename = "RATECODE"
>                 DBFIELDINFO(DBS_ALIAS, FieldPos("code"), "_code")
>             CASE cFilename = "TICKET"
>                 DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
>             CASE cFilename = "INVOICE"
>                 DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
>             CASE cFilename = "HISTORY"
>                 DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
>         ENDCASE
>     ENDIF
>     RETURN lRet
> FUNCTION AddDbfQuiet()
>     LOCAL nTries := 0 AS INT
>
>     EnterCriticalSection(@CS_WATCHERR)
>     WHILE nTries < 10
>
>            DBAPPEND(TRUE)
>            IF !NetErr()
>                LeaveCriticalSection(@CS_WATCHERR)
>               RETURN TRUE
>            ENDIF
>            ++nTries
>            Sleep(50)
>     ENDDO
>     LeaveCriticalSection(@CS_WATCHERR)
>     RETURN FALSE
> FUNCTION EditDbf()
>     LOCAL nTries := 0 AS INT
>
>     WHILE nTries < 10
>         ++nTries
>         //IF DBRLOCK(RECNO())
>         IF DBRLOCK()
>             RETURN TRUE
>         ENDIF
>         IF nTries < 5
>             Sleep(100)
>             LOOP
>         ENDIF
>         IF MessageBox(0, PSZ("Unable to lock record"), ;
>             PSZ("Record Lock Failure"), MB_RETRYCANCEL +
> MB_ICONEXCLAMATION) != IDRETRY
>             RETURN FALSE
>         ENDIF
>     ENDDO
>     RETURN FALSE
> FUNCTION OpenDbfQuiet(cFilename, cAliasname, lExclusive)
>     LOCAL nTries := 0 AS INT
>
>     EnterCriticalSection(@CS_WATCHERR)
>     IF IsNil(lExclusive)
>         lExclusive := FALSE
>     ENDIF
>     IF IsNil(cAliasname)
>         cAliasname := cFilename
>     ENDIF
>     IF SELECT(cAliasname) != 0    // Alias already in use
>         cAliasname := Symbol2String(ConstructUniqueAlias(cFilename))
>     ENDIF
>
>     WHILE nTries < 10
>         ++nTries
>         DBUSEAREA(TRUE, "DBFCDX", cFilename, cAliasname, !lExclusive,
> FALSE)
>         IF !NetErr()
>             LeaveCriticalSection(@CS_WATCHERR)
>             RETURN TRUE
>         ENDIF
>         Sleep(50)
>     END
>     LeaveCriticalSection(@CS_WATCHERR)
>     RETURN FALSE
>
> Ginny
>
> "Martin"  wrote in message news:QGkwt.122934$G56.87814@fx32.fr7...
>
> Very interesting, you are using direct DBF rather than servers, I will
> try that thankyou
>
> On 19/06/2013 15:02, Ginny Caughey wrote:
>> Martin,
>>
>> I'm really not seeing anything obviously wrong here. Have you tried it
>> without the Dynlock/Dynunlock? Here's my threaded code that ran without
>> issues for several years. Maybe you'll spot something useful:
>>
>> FUNCTION RunPollingLoop( pInfo AS WatchInfo ) AS DWORD PASCAL    //
>> Threaded function
>>     LOCAL uMsg IS _winMsg    // used by thread message loop
>>     LOCAL aParity AS ARRAY
>>     LOCAL i AS INT
>>     LOCAL cScale, cParity AS STRING
>>     LOCAL nWeight, nTopWeight, nMinimumWt, nDelay AS INT
>>     LOCAL dwStop AS DWORD
>>     LOCAL dDate AS DATE
>>     LOCAL cTime AS STRING
>>     LOCAL oReader AS ScaleWatcher    // object that actually reads the
>> scale and performs NTEP weight validation
>>     LOCAL control, watchman, wconfig AS DWORD    // workareas for dbf
>> files
>>     LOCAL lError AS LOGIC
>>
>>     // Update status bar with scale started text
>>     PostMessage(pInfo.hWnd, MSG_StartStop, pInfo.ScaleNumber,
>> ScaleStarted)
>>
>>     // read paramters for this scale from wconfig and control files
>>     aParity := { {"E", EvenParity}, ;
>>                 {"M", MarkParity}, ;
>>                 {"N", NoParity}, ;
>>                 {"O", OddParity}, ;
>>                 {"S", SpaceParity}     }
>>
>>     BEGIN SEQUENCE
>>         IF !OpenDbfQuiet("control")
>>             BREAK
>>         ENDIF
>>         control := DBGETSELECT()
>>         IF !OpenDbfQuiet("wconfig")
>>             BREAK
>>         ENDIF
>>         wconfig := DBGETSELECT()
>>         IF !OpenDbfQuiet("watchman")
>>             BREAK
>>         ENDIF
>>         watchman := DBGETSELECT()
>>     RECOVER
>>         lError := TRUE
>>         HandleError("Unable to open a file needed to run Watchman Mode
>> processing.")
>>         IF control > 0
>>             DBSELECTAREA(control)
>>             DBCLOSEAREA()
>>         ENDIF
>>         IF wconfig > 0
>>             DBSELECTAREA(wconfig)
>>             DBCLOSEAREA()
>>         ENDIF
>>         IF watchman > 0
>>             DBSELECTAREA(watchman)
>>             DBCLOSEAREA()
>>         ENDIF
>>     END SEQUENCE
>>
>>     IF lError
>>         RETURN 0
>>     ENDIF
>>
>>     PostMessage(pInfo.hWnd, MSG_GettingData, pInfo.ScaleNumber, 0)
>>     oReader := ScaleWatcher{pInfo.hWnd}
>>     oReader:CommPort := "Com"+ NTrim(pInfo.PortNumber)
>>     Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Getting info for
>> scale")
>>
>>     // Get info for this scale port from control file
>>     cScale := Str(pInfo.ScaleNumber,1,0)
>>     nMinimumWt := (wconfig)->minimumwt
>>     nDelay := (wconfig)->interval
>>     (wconfig)->(DBCLOSEAREA())
>>
>>     oReader:Baud := (control)->(FIELDGET(FieldPos("baud"+cScale)))
>>     oReader:Databits :=
>> (control)->(FIELDGET(FieldPos("databits"+cScale)))
>>     oReader:Stopbits :=
>> (control)->(FIELDGET(FieldPos("stopbits"+cScale)))
>>     IF oReader:Stopbits = 1
>>         oReader:Stopbits := OneStopBit    // convert to Windows value (2
>> = TwoStopBits already)
>>     ENDIF
>>     cParity := (control)->(FIELDGET(FieldPos("parity"+cScale)))
>>     i := AScan(aParity, {|aVal| aVal[1] = cParity})
>>     IF i > 0
>>         oReader:Parity := aParity[i,2]
>>     ELSE
>>         oReader:Parity := NoParity
>>     ENDIF
>>     oReader:Buffsize :=
>> (control)->(FIELDGET(FieldPos("buffsize"+cScale)))
>>     oReader:WtBegin :=  (control)->(FIELDGET(FieldPos("wtbegin"+cScale)))
>>     oReader:WtLength :=
>> (control)->(FIELDGET(FieldPos("wtlength"+cScale)))
>>     oReader:CheckChar :=
>> (control)->(FIELDGET(FieldPos("poll1chr"+cScale)))
>>     oReader:CheckPosition :=
>> (control)->(FIELDGET(FieldPos("poll2chr"+cScale)))
>>     oReader:MaxRetries :=
>> (control)->(FIELDGET(FieldPos("poll3chr"+cScale)))
>>     oReader:MotionChar :=
>> (control)->(FIELDGET(FieldPos("poll4chr"+cScale)))
>>     oReader:MotionByte := (control)->(FIELDGET(FieldPos("ack"+cScale)))
>>     oReader:GrossLoc :=
>> (control)->(FIELDGET(FieldPos("grossloc"+cScale)))
>>     oReader:UnitLoc := (control)->(FIELDGET(FieldPos("unitloc"+cScale)))
>>     oReader:ScaleUnit := (control)->(FIELDGET(FieldPos("scaleunit")))
>>     (control)->(DBCLOSEAREA())
>>
>>     // Run polling loop until WM_QUIT received from primary thread
>>     // Polling is a two step process here:
>>     //    1. Sample every nDelay seconds for a weigh large enough to
>> indicate a vehicle
>>     //    2. Once a vehicle is on the scale, sample at 1/10 second
>> intervals to catch maximum weight
>>     WHILE TRUE
>>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - In polling loop")
>>         //PostMessage(pInfo.hWnd, MSG_Polling, pInfo.ScaleNumber, 0)
>>         IF PeekMessage(@uMsg, 0, 0, 0, PM_REMOVE)    // PeekMessage
>> returns true if any messages in queue
>>             IF uMsg.message == WM_QUIT
>>                 EXIT
>>             ENDIF
>>         ENDIF
>>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Getting first
>> weight")
>>         nWeight := oReader:ReadScale()
>>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - nWeight is
>> "+NTrim(nWeight))
>>         IF oReader:CancelRequested
>>             EXIT
>>         ENDIF
>>         IF nWeight = -1    // Error occurred
>>             PostMessage(pInfo.hWnd, MSG_ScaleError, pInfo.ScaleNumber, 0)
>>         ELSEIF nWeight < nMinimumWt
>>             dwStop := GetTickCountLow()+DWORD(nDelay * 1000)
>>             //PostMessage(pInfo.hWnd, MSG_Polling, pInfo.ScaleNumber, 0)
>>             WHILE GetTickCountLow() <= dwStop
>>                 IF PeekMessage(@uMsg, 0, 0, 0, PM_REMOVE)
>>                     IF uMsg.message == WM_QUIT
>>                         EXIT
>>                     ENDIF
>>                 ENDIF
>>             END
>>         ELSE
>>             // We have a vehicle on scale
>>             // Sample every 1/10 second until its maximum weight is
>> captured
>>             PostMessage(pInfo.hWnd, MSG_Sampling, pInfo.ScaleNumber, 0)
>>             nTopWeight := nWeight
>>             dDate := Today()
>>             cTime := Time24()
>>             WHILE TRUE
>>                 IF PeekMessage(@uMsg, 0, 0, 0, PM_NOREMOVE)
>>                     IF uMsg.message == WM_QUIT
>>                         EXIT
>>                     ENDIF
>>                 ENDIF
>>                 Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Testing
>> for maximum weight")
>>                 nWeight := oReader:ReadScale()
>>                 IF oReader:CancelRequested
>>                     EXIT
>>                 ENDIF
>>                 IF nWeight < nMinimumWt .AND. !oReader:MotionDetected
>>                     EXIT
>>                 ENDIF
>>                 IF nWeight > nTopWeight
>>                     nTopWeight := nWeight
>>                     dDate := Today()
>>                     cTime := Time24()
>>                 ENDIF
>>                 Sleep(100)    // give time slice to other threads for
>> 1/10 second
>>             END
>>             IF uMsg.message != WM_QUIT .AND. !oReader:CancelRequested
>>                 // Write out weight to file using file sharing
>>                 IF (watchman)->(AddDbfQuiet())
>>                     (watchman)->today := dDate
>>                     (watchman)->time24 := cTime
>>                     (watchman)->weight := nTopWeight
>>                     (watchman)->scaleno := Str(pInfo.ScaleNumber,1,0)
>>                     (watchman)->(DBCOMMIT())
>>                     (watchman)->(DBUNLOCK())
>>                 ELSE
>>                     HandleError("Unable to add a record to the watchman
>> file.")
>>                 ENDIF
>>             ELSE
>>                 EXIT
>>             ENDIF
>>         ENDIF
>>         IF uMsg.message == WM_QUIT .OR. oReader:CancelRequested
>>             EXIT
>>         ENDIF
>>     END
>>     Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Shutting down thread")
>>     (watchman)->(DBCLOSEAREA())
>>     RETURN 0
>> FUNCTION Output( s AS STRING ) AS VOID PASCAL    // thread-safe way to
>> write to log file
>>     IF hDebug != NULL_PTR
>>         EnterCriticalSection(@CS_DEBUG)
>>         FWriteLine(hDebug, s)
>>         LeaveCriticalSection(@CS_DEBUG)
>>     ENDIF
>>     RETURN
>> FUNCTION HandleError(cError AS STRING) AS VOID PASCAL
>>     LOCAL hFile AS PTR
>>
>>     // Thread-safe write to log file
>>     EnterCriticalSection(@CS_WATCHERR)
>>     IF File(GetDefault()+"watcherr.log")
>>         hFile := FOpen(GetDefault()+"watcherr.log", FO_READWRITE)
>>         FSeek(hFile, 0, FS_END)
>>     ELSE
>>         hFile := FCreate(GetDefault()+"watcherr.log")
>>     ENDIF
>>     IF hFile != F_ERROR
>>         FWrite(hFile, DToC(Today())+" "+Time24()+"
>> "+cError+_CHR(13)+_CHR(10))
>>         FClose(hFile)
>>     ENDIF
>>     LeaveCriticalSection(@CS_WATCHERR)
>> Ginny
>>
>> "Martin"  wrote in message news:vMgwt.107261$4C2.78184@fx23.fr7...
>>
>> Here we go Ginny
>>
>>
>> Thanks
>>
>> Martin
>> 

[toc] | [prev] | [next] | [standalone]


#5393

From"Martin \(BT\)" <martin-spam@btinternet.com>
Date2013-06-20 20:27 +0100
Message-ID<z5idnQZjZaab9V7MnZ2dnUVZ8uSdnZ2d@bt.com>
In reply to#5392
I think I will have to go down the seperate .exe route, not good, but I have 
linked in a few thousand lines of library code.


"Ginny Caughey" <gcaughey@online.hotmail.com> wrote in message 
news:51c34422$0$57923$c3e8da3$eb767761@news.astraweb.com...
> If your UI thread is accessing DBF files without using the same DBF 
> functions as the worker thread, that could be the issue.
>
> Ginny
>
> "Martin"  wrote in message news:ARFwt.114422$P_4.83439@fx31.fr7...
>
> Thanks Ginny
>
> Just been testing since we have got the server running (blew up after
> power cut despite UPS), with thread running the scanning code (main
> .exe) crashes accessing the barcode system. thread carries on running
> until I quit.
>
> Not using servers in thread, but Clipper style, any access controlled
> with critical sections
>
> Note the same type of error in two files, both are open in the thread
> with their own opens.
>
> Arg:             uField
> ArgNum:          0
> Args:          1 BC_ORDER : SYMBOL
> ArgType:         NIL
> ArgTypeReq:      NIL
> CallFuncSym:     FIELDGET
> CanDefault:      .F.
> CanRetry:        .F.
> CanSubstitute:   .F.
> Description:     Wrong field specification
>
>
>
> Error Detail
> Arg:             uField
> ArgNum:          0
> Args:          1 PL_DATE : SYMBOL
> ArgType:         NIL
> ArgTypeReq:      NIL
> CallFuncSym:     FIELDGET
> CanDefault:      .F.
> CanRetry:        .F.
> CanSubstitute:   .F.
> Description:     Wrong field specification
> FileHandle:      0
> FileName:
> FuncPtr:         0x00000000
> FuncSym:         FIELDGET
> GenCode:         1 : Argument error
> MaxSize:         0
> MethodSelf:      BarList
> Operation:
> OsCode:          0 : Successful completion
> Severity:        ERROR
> SubCode:         0
> SubCodeText:
> SubstituteType:  NIL
> SubSystem:       Database
> Tries:           0
>
>
>
>
> On 20/06/2013 12:22, Ginny Caughey wrote:
>> Here are the wrapper functions I'm using:
>>
>> FUNCTION AddDbf()
>>     LOCAL dwStop AS DWORD
>>
>>     WHILE TRUE
>>         dwStop := GetTickCountLow()+5000
>>         WHILE GetTickCountLow() < dwStop
>>                DBAPPEND()
>>                IF ! NetErr()
>>                   RETURN TRUE
>>                ENDIF
>>                Sleep(100)
>>         ENDDO
>>         IF MessageBox(0, PSZ("Unable to add a record to file"), ;
>>             PSZ("Append Failure"), MB_RETRYCANCEL + MB_ICONEXCLAMATION)
>> != IDRETRY
>>             EXIT
>>         ENDIF
>>     END
>>     RETURN FALSE
>> STATIC FUNCTION ConstructUniqueAlias( cFileName AS STRING ) AS SYMBOL
>> PASCAL
>>     // Borrowed from 1.0c SDK in dbfsrvr.prg
>>     LOCAL cTryNewAlias AS STRING
>>     LOCAL w AS DWORD
>>
>>     IF IsNil(cFileName)
>>         cFileName := "NOFILENAME"
>>     ELSEIF ( w := At( ".", cFileName ) )>0
>>         cFileName := SubStr( cFileName, 1, w-1 )
>>     ENDIF
>>     w := 1
>>     cTryNewAlias := Upper(cFileName)
>>
>>     DO WHILE VODBSymSelect( String2Symbol( cTryNewAlias ) )>0
>>         cTryNewAlias := Upper(cFileName)+"_"+AllTrim( Str( w++ ) )
>>     ENDDO
>>
>>     RETURN String2Symbol(cTryNewAlias)
>> FUNCTION XOpenDBF(cFilename)
>>     RETURN OpenDbf(cFilename, , TRUE)
>> FUNCTION OpenDbf(cFilename, cAliasname, lExclusive)
>>     LOCAL dwStop AS DWORD
>>     LOCAL lRet AS LOGIC
>>
>>     IF IsNil(lExclusive)
>>         lExclusive := FALSE
>>     ENDIF
>>     IF IsNil(cAliasname)
>>         cAliasname := cFilename
>>     ENDIF
>>     IF SELECT(cAliasname) != 0    // Alias already in use
>>         cAliasname := Symbol2String(ConstructUniqueAlias(cFilename))
>>     ENDIF
>>     BEGIN SEQUENCE
>>         WHILE TRUE
>>             dwStop := GetTickCountLow()+5000 // allow .5 sec. retry
>>             WHILE GetTickCountLow() <= dwStop
>>                 Sleep(100)
>>                 DBUSEAREA(TRUE, , cFilename, cAliasname, !lExclusive,
>> FALSE)
>>                 // use (cFilename) ALIAS (cAliasname) shared new
>>                 IF ! NetErr()
>>                     lRet := TRUE
>>                     BREAK
>>                 ENDIF
>>             END
>>             IF MessageBox(0, PSZ("Unable to open file "+cFilename), ;
>>                 PSZ("File Open Error"), MB_RETRYCANCEL +
>> MB_ICONEXCLAMATION) != IDRETRY
>>                 EXIT
>>             ENDIF
>>         ENDDO
>>     END SEQUENCE
>>     IF lRet
>>         cFilename := Upper(cFilename)
>>         DO CASE
>>             CASE cFilename = "RATECODE"
>>                 DBFIELDINFO(DBS_ALIAS, FieldPos("code"), "_code")
>>             CASE cFilename = "TICKET"
>>                 DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
>>             CASE cFilename = "INVOICE"
>>                 DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
>>             CASE cFilename = "HISTORY"
>>                 DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
>>         ENDCASE
>>     ENDIF
>>     RETURN lRet
>> FUNCTION AddDbfQuiet()
>>     LOCAL nTries := 0 AS INT
>>
>>     EnterCriticalSection(@CS_WATCHERR)
>>     WHILE nTries < 10
>>
>>            DBAPPEND(TRUE)
>>            IF !NetErr()
>>                LeaveCriticalSection(@CS_WATCHERR)
>>               RETURN TRUE
>>            ENDIF
>>            ++nTries
>>            Sleep(50)
>>     ENDDO
>>     LeaveCriticalSection(@CS_WATCHERR)
>>     RETURN FALSE
>> FUNCTION EditDbf()
>>     LOCAL nTries := 0 AS INT
>>
>>     WHILE nTries < 10
>>         ++nTries
>>         //IF DBRLOCK(RECNO())
>>         IF DBRLOCK()
>>             RETURN TRUE
>>         ENDIF
>>         IF nTries < 5
>>             Sleep(100)
>>             LOOP
>>         ENDIF
>>         IF MessageBox(0, PSZ("Unable to lock record"), ;
>>             PSZ("Record Lock Failure"), MB_RETRYCANCEL +
>> MB_ICONEXCLAMATION) != IDRETRY
>>             RETURN FALSE
>>         ENDIF
>>     ENDDO
>>     RETURN FALSE
>> FUNCTION OpenDbfQuiet(cFilename, cAliasname, lExclusive)
>>     LOCAL nTries := 0 AS INT
>>
>>     EnterCriticalSection(@CS_WATCHERR)
>>     IF IsNil(lExclusive)
>>         lExclusive := FALSE
>>     ENDIF
>>     IF IsNil(cAliasname)
>>         cAliasname := cFilename
>>     ENDIF
>>     IF SELECT(cAliasname) != 0    // Alias already in use
>>         cAliasname := Symbol2String(ConstructUniqueAlias(cFilename))
>>     ENDIF
>>
>>     WHILE nTries < 10
>>         ++nTries
>>         DBUSEAREA(TRUE, "DBFCDX", cFilename, cAliasname, !lExclusive,
>> FALSE)
>>         IF !NetErr()
>>             LeaveCriticalSection(@CS_WATCHERR)
>>             RETURN TRUE
>>         ENDIF
>>         Sleep(50)
>>     END
>>     LeaveCriticalSection(@CS_WATCHERR)
>>     RETURN FALSE
>>
>> Ginny
>>
>> "Martin"  wrote in message news:QGkwt.122934$G56.87814@fx32.fr7...
>>
>> Very interesting, you are using direct DBF rather than servers, I will
>> try that thankyou
>>
>> On 19/06/2013 15:02, Ginny Caughey wrote:
>>> Martin,
>>>
>>> I'm really not seeing anything obviously wrong here. Have you tried it
>>> without the Dynlock/Dynunlock? Here's my threaded code that ran without
>>> issues for several years. Maybe you'll spot something useful:
>>>
>>> FUNCTION RunPollingLoop( pInfo AS WatchInfo ) AS DWORD PASCAL    //
>>> Threaded function
>>>     LOCAL uMsg IS _winMsg    // used by thread message loop
>>>     LOCAL aParity AS ARRAY
>>>     LOCAL i AS INT
>>>     LOCAL cScale, cParity AS STRING
>>>     LOCAL nWeight, nTopWeight, nMinimumWt, nDelay AS INT
>>>     LOCAL dwStop AS DWORD
>>>     LOCAL dDate AS DATE
>>>     LOCAL cTime AS STRING
>>>     LOCAL oReader AS ScaleWatcher    // object that actually reads the
>>> scale and performs NTEP weight validation
>>>     LOCAL control, watchman, wconfig AS DWORD    // workareas for dbf
>>> files
>>>     LOCAL lError AS LOGIC
>>>
>>>     // Update status bar with scale started text
>>>     PostMessage(pInfo.hWnd, MSG_StartStop, pInfo.ScaleNumber,
>>> ScaleStarted)
>>>
>>>     // read paramters for this scale from wconfig and control files
>>>     aParity := { {"E", EvenParity}, ;
>>>                 {"M", MarkParity}, ;
>>>                 {"N", NoParity}, ;
>>>                 {"O", OddParity}, ;
>>>                 {"S", SpaceParity}     }
>>>
>>>     BEGIN SEQUENCE
>>>         IF !OpenDbfQuiet("control")
>>>             BREAK
>>>         ENDIF
>>>         control := DBGETSELECT()
>>>         IF !OpenDbfQuiet("wconfig")
>>>             BREAK
>>>         ENDIF
>>>         wconfig := DBGETSELECT()
>>>         IF !OpenDbfQuiet("watchman")
>>>             BREAK
>>>         ENDIF
>>>         watchman := DBGETSELECT()
>>>     RECOVER
>>>         lError := TRUE
>>>         HandleError("Unable to open a file needed to run Watchman Mode
>>> processing.")
>>>         IF control > 0
>>>             DBSELECTAREA(control)
>>>             DBCLOSEAREA()
>>>         ENDIF
>>>         IF wconfig > 0
>>>             DBSELECTAREA(wconfig)
>>>             DBCLOSEAREA()
>>>         ENDIF
>>>         IF watchman > 0
>>>             DBSELECTAREA(watchman)
>>>             DBCLOSEAREA()
>>>         ENDIF
>>>     END SEQUENCE
>>>
>>>     IF lError
>>>         RETURN 0
>>>     ENDIF
>>>
>>>     PostMessage(pInfo.hWnd, MSG_GettingData, pInfo.ScaleNumber, 0)
>>>     oReader := ScaleWatcher{pInfo.hWnd}
>>>     oReader:CommPort := "Com"+ NTrim(pInfo.PortNumber)
>>>     Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Getting info for
>>> scale")
>>>
>>>     // Get info for this scale port from control file
>>>     cScale := Str(pInfo.ScaleNumber,1,0)
>>>     nMinimumWt := (wconfig)->minimumwt
>>>     nDelay := (wconfig)->interval
>>>     (wconfig)->(DBCLOSEAREA())
>>>
>>>     oReader:Baud := (control)->(FIELDGET(FieldPos("baud"+cScale)))
>>>     oReader:Databits :=
>>> (control)->(FIELDGET(FieldPos("databits"+cScale)))
>>>     oReader:Stopbits :=
>>> (control)->(FIELDGET(FieldPos("stopbits"+cScale)))
>>>     IF oReader:Stopbits = 1
>>>         oReader:Stopbits := OneStopBit    // convert to Windows value (2
>>> = TwoStopBits already)
>>>     ENDIF
>>>     cParity := (control)->(FIELDGET(FieldPos("parity"+cScale)))
>>>     i := AScan(aParity, {|aVal| aVal[1] = cParity})
>>>     IF i > 0
>>>         oReader:Parity := aParity[i,2]
>>>     ELSE
>>>         oReader:Parity := NoParity
>>>     ENDIF
>>>     oReader:Buffsize :=
>>> (control)->(FIELDGET(FieldPos("buffsize"+cScale)))
>>>     oReader:WtBegin := 
>>> (control)->(FIELDGET(FieldPos("wtbegin"+cScale)))
>>>     oReader:WtLength :=
>>> (control)->(FIELDGET(FieldPos("wtlength"+cScale)))
>>>     oReader:CheckChar :=
>>> (control)->(FIELDGET(FieldPos("poll1chr"+cScale)))
>>>     oReader:CheckPosition :=
>>> (control)->(FIELDGET(FieldPos("poll2chr"+cScale)))
>>>     oReader:MaxRetries :=
>>> (control)->(FIELDGET(FieldPos("poll3chr"+cScale)))
>>>     oReader:MotionChar :=
>>> (control)->(FIELDGET(FieldPos("poll4chr"+cScale)))
>>>     oReader:MotionByte := (control)->(FIELDGET(FieldPos("ack"+cScale)))
>>>     oReader:GrossLoc :=
>>> (control)->(FIELDGET(FieldPos("grossloc"+cScale)))
>>>     oReader:UnitLoc := (control)->(FIELDGET(FieldPos("unitloc"+cScale)))
>>>     oReader:ScaleUnit := (control)->(FIELDGET(FieldPos("scaleunit")))
>>>     (control)->(DBCLOSEAREA())
>>>
>>>     // Run polling loop until WM_QUIT received from primary thread
>>>     // Polling is a two step process here:
>>>     //    1. Sample every nDelay seconds for a weigh large enough to
>>> indicate a vehicle
>>>     //    2. Once a vehicle is on the scale, sample at 1/10 second
>>> intervals to catch maximum weight
>>>     WHILE TRUE
>>>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - In polling loop")
>>>         //PostMessage(pInfo.hWnd, MSG_Polling, pInfo.ScaleNumber, 0)
>>>         IF PeekMessage(@uMsg, 0, 0, 0, PM_REMOVE)    // PeekMessage
>>> returns true if any messages in queue
>>>             IF uMsg.message == WM_QUIT
>>>                 EXIT
>>>             ENDIF
>>>         ENDIF
>>>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Getting first
>>> weight")
>>>         nWeight := oReader:ReadScale()
>>>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - nWeight is
>>> "+NTrim(nWeight))
>>>         IF oReader:CancelRequested
>>>             EXIT
>>>         ENDIF
>>>         IF nWeight = -1    // Error occurred
>>>             PostMessage(pInfo.hWnd, MSG_ScaleError, pInfo.ScaleNumber, 
>>> 0)
>>>         ELSEIF nWeight < nMinimumWt
>>>             dwStop := GetTickCountLow()+DWORD(nDelay * 1000)
>>>             //PostMessage(pInfo.hWnd, MSG_Polling, pInfo.ScaleNumber, 0)
>>>             WHILE GetTickCountLow() <= dwStop
>>>                 IF PeekMessage(@uMsg, 0, 0, 0, PM_REMOVE)
>>>                     IF uMsg.message == WM_QUIT
>>>                         EXIT
>>>                     ENDIF
>>>                 ENDIF
>>>             END
>>>         ELSE
>>>             // We have a vehicle on scale
>>>             // Sample every 1/10 second until its maximum weight is
>>> captured
>>>             PostMessage(pInfo.hWnd, MSG_Sampling, pInfo.ScaleNumber, 0)
>>>             nTopWeight := nWeight
>>>             dDate := Today()
>>>             cTime := Time24()
>>>             WHILE TRUE
>>>                 IF PeekMessage(@uMsg, 0, 0, 0, PM_NOREMOVE)
>>>                     IF uMsg.message == WM_QUIT
>>>                         EXIT
>>>                     ENDIF
>>>                 ENDIF
>>>                 Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Testing
>>> for maximum weight")
>>>                 nWeight := oReader:ReadScale()
>>>                 IF oReader:CancelRequested
>>>                     EXIT
>>>                 ENDIF
>>>                 IF nWeight < nMinimumWt .AND. !oReader:MotionDetected
>>>                     EXIT
>>>                 ENDIF
>>>                 IF nWeight > nTopWeight
>>>                     nTopWeight := nWeight
>>>                     dDate := Today()
>>>                     cTime := Time24()
>>>                 ENDIF
>>>                 Sleep(100)    // give time slice to other threads for
>>> 1/10 second
>>>             END
>>>             IF uMsg.message != WM_QUIT .AND. !oReader:CancelRequested
>>>                 // Write out weight to file using file sharing
>>>                 IF (watchman)->(AddDbfQuiet())
>>>                     (watchman)->today := dDate
>>>                     (watchman)->time24 := cTime
>>>                     (watchman)->weight := nTopWeight
>>>                     (watchman)->scaleno := Str(pInfo.ScaleNumber,1,0)
>>>                     (watchman)->(DBCOMMIT())
>>>                     (watchman)->(DBUNLOCK())
>>>                 ELSE
>>>                     HandleError("Unable to add a record to the watchman
>>> file.")
>>>                 ENDIF
>>>             ELSE
>>>                 EXIT
>>>             ENDIF
>>>         ENDIF
>>>         IF uMsg.message == WM_QUIT .OR. oReader:CancelRequested
>>>             EXIT
>>>         ENDIF
>>>     END
>>>     Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Shutting down 
>>> thread")
>>>     (watchman)->(DBCLOSEAREA())
>>>     RETURN 0
>>> FUNCTION Output( s AS STRING ) AS VOID PASCAL    // thread-safe way to
>>> write to log file
>>>     IF hDebug != NULL_PTR
>>>         EnterCriticalSection(@CS_DEBUG)
>>>         FWriteLine(hDebug, s)
>>>         LeaveCriticalSection(@CS_DEBUG)
>>>     ENDIF
>>>     RETURN
>>> FUNCTION HandleError(cError AS STRING) AS VOID PASCAL
>>>     LOCAL hFile AS PTR
>>>
>>>     // Thread-safe write to log file
>>>     EnterCriticalSection(@CS_WATCHERR)
>>>     IF File(GetDefault()+"watcherr.log")
>>>         hFile := FOpen(GetDefault()+"watcherr.log", FO_READWRITE)
>>>         FSeek(hFile, 0, FS_END)
>>>     ELSE
>>>         hFile := FCreate(GetDefault()+"watcherr.log")
>>>     ENDIF
>>>     IF hFile != F_ERROR
>>>         FWrite(hFile, DToC(Today())+" "+Time24()+"
>>> "+cError+_CHR(13)+_CHR(10))
>>>         FClose(hFile)
>>>     ENDIF
>>>     LeaveCriticalSection(@CS_WATCHERR)
>>> Ginny
>>>
>>> "Martin"  wrote in message news:vMgwt.107261$4C2.78184@fx23.fr7...
>>>
>>> Here we go Ginny
>>>
>>>
>>> Thanks
>>>
>>> Martin
>>>
> 

[toc] | [prev] | [next] | [standalone]


#5395

From"Ginny Caughey" <gcaughey@online.hotmail.com>
Date2013-06-21 06:54 -0400
Message-ID<51c430bb$0$58329$c3e8da3$88b277c5@news.astraweb.com>
In reply to#5393
I really think you'll be happier with that approach. Multithreading can work 
in VO with DBF access, but it's tricky. The communication between windows 
using PostMessage used inside a multithreaded app can also be used across 
apps, so there's no real advantage to having everything in one app.

Ginny

"Martin (BT)"  wrote in message 
news:z5idnQZjZaab9V7MnZ2dnUVZ8uSdnZ2d@bt.com...

I think I will have to go down the seperate .exe route, not good, but I have
linked in a few thousand lines of library code.


"Ginny Caughey" <gcaughey@online.hotmail.com> wrote in message
news:51c34422$0$57923$c3e8da3$eb767761@news.astraweb.com...
> If your UI thread is accessing DBF files without using the same DBF 
> functions as the worker thread, that could be the issue.
>
> Ginny
>
> "Martin"  wrote in message news:ARFwt.114422$P_4.83439@fx31.fr7...
>
> Thanks Ginny
>
> Just been testing since we have got the server running (blew up after
> power cut despite UPS), with thread running the scanning code (main
> .exe) crashes accessing the barcode system. thread carries on running
> until I quit.
>
> Not using servers in thread, but Clipper style, any access controlled
> with critical sections
>
> Note the same type of error in two files, both are open in the thread
> with their own opens.
>
> Arg:             uField
> ArgNum:          0
> Args:          1 BC_ORDER : SYMBOL
> ArgType:         NIL
> ArgTypeReq:      NIL
> CallFuncSym:     FIELDGET
> CanDefault:      .F.
> CanRetry:        .F.
> CanSubstitute:   .F.
> Description:     Wrong field specification
>
>
>
> Error Detail
> Arg:             uField
> ArgNum:          0
> Args:          1 PL_DATE : SYMBOL
> ArgType:         NIL
> ArgTypeReq:      NIL
> CallFuncSym:     FIELDGET
> CanDefault:      .F.
> CanRetry:        .F.
> CanSubstitute:   .F.
> Description:     Wrong field specification
> FileHandle:      0
> FileName:
> FuncPtr:         0x00000000
> FuncSym:         FIELDGET
> GenCode:         1 : Argument error
> MaxSize:         0
> MethodSelf:      BarList
> Operation:
> OsCode:          0 : Successful completion
> Severity:        ERROR
> SubCode:         0
> SubCodeText:
> SubstituteType:  NIL
> SubSystem:       Database
> Tries:           0
>
>
>
>
> On 20/06/2013 12:22, Ginny Caughey wrote:
>> Here are the wrapper functions I'm using:
>>
>> FUNCTION AddDbf()
>>     LOCAL dwStop AS DWORD
>>
>>     WHILE TRUE
>>         dwStop := GetTickCountLow()+5000
>>         WHILE GetTickCountLow() < dwStop
>>                DBAPPEND()
>>                IF ! NetErr()
>>                   RETURN TRUE
>>                ENDIF
>>                Sleep(100)
>>         ENDDO
>>         IF MessageBox(0, PSZ("Unable to add a record to file"), ;
>>             PSZ("Append Failure"), MB_RETRYCANCEL + MB_ICONEXCLAMATION)
>> != IDRETRY
>>             EXIT
>>         ENDIF
>>     END
>>     RETURN FALSE
>> STATIC FUNCTION ConstructUniqueAlias( cFileName AS STRING ) AS SYMBOL
>> PASCAL
>>     // Borrowed from 1.0c SDK in dbfsrvr.prg
>>     LOCAL cTryNewAlias AS STRING
>>     LOCAL w AS DWORD
>>
>>     IF IsNil(cFileName)
>>         cFileName := "NOFILENAME"
>>     ELSEIF ( w := At( ".", cFileName ) )>0
>>         cFileName := SubStr( cFileName, 1, w-1 )
>>     ENDIF
>>     w := 1
>>     cTryNewAlias := Upper(cFileName)
>>
>>     DO WHILE VODBSymSelect( String2Symbol( cTryNewAlias ) )>0
>>         cTryNewAlias := Upper(cFileName)+"_"+AllTrim( Str( w++ ) )
>>     ENDDO
>>
>>     RETURN String2Symbol(cTryNewAlias)
>> FUNCTION XOpenDBF(cFilename)
>>     RETURN OpenDbf(cFilename, , TRUE)
>> FUNCTION OpenDbf(cFilename, cAliasname, lExclusive)
>>     LOCAL dwStop AS DWORD
>>     LOCAL lRet AS LOGIC
>>
>>     IF IsNil(lExclusive)
>>         lExclusive := FALSE
>>     ENDIF
>>     IF IsNil(cAliasname)
>>         cAliasname := cFilename
>>     ENDIF
>>     IF SELECT(cAliasname) != 0    // Alias already in use
>>         cAliasname := Symbol2String(ConstructUniqueAlias(cFilename))
>>     ENDIF
>>     BEGIN SEQUENCE
>>         WHILE TRUE
>>             dwStop := GetTickCountLow()+5000 // allow .5 sec. retry
>>             WHILE GetTickCountLow() <= dwStop
>>                 Sleep(100)
>>                 DBUSEAREA(TRUE, , cFilename, cAliasname, !lExclusive,
>> FALSE)
>>                 // use (cFilename) ALIAS (cAliasname) shared new
>>                 IF ! NetErr()
>>                     lRet := TRUE
>>                     BREAK
>>                 ENDIF
>>             END
>>             IF MessageBox(0, PSZ("Unable to open file "+cFilename), ;
>>                 PSZ("File Open Error"), MB_RETRYCANCEL +
>> MB_ICONEXCLAMATION) != IDRETRY
>>                 EXIT
>>             ENDIF
>>         ENDDO
>>     END SEQUENCE
>>     IF lRet
>>         cFilename := Upper(cFilename)
>>         DO CASE
>>             CASE cFilename = "RATECODE"
>>                 DBFIELDINFO(DBS_ALIAS, FieldPos("code"), "_code")
>>             CASE cFilename = "TICKET"
>>                 DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
>>             CASE cFilename = "INVOICE"
>>                 DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
>>             CASE cFilename = "HISTORY"
>>                 DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
>>         ENDCASE
>>     ENDIF
>>     RETURN lRet
>> FUNCTION AddDbfQuiet()
>>     LOCAL nTries := 0 AS INT
>>
>>     EnterCriticalSection(@CS_WATCHERR)
>>     WHILE nTries < 10
>>
>>            DBAPPEND(TRUE)
>>            IF !NetErr()
>>                LeaveCriticalSection(@CS_WATCHERR)
>>               RETURN TRUE
>>            ENDIF
>>            ++nTries
>>            Sleep(50)
>>     ENDDO
>>     LeaveCriticalSection(@CS_WATCHERR)
>>     RETURN FALSE
>> FUNCTION EditDbf()
>>     LOCAL nTries := 0 AS INT
>>
>>     WHILE nTries < 10
>>         ++nTries
>>         //IF DBRLOCK(RECNO())
>>         IF DBRLOCK()
>>             RETURN TRUE
>>         ENDIF
>>         IF nTries < 5
>>             Sleep(100)
>>             LOOP
>>         ENDIF
>>         IF MessageBox(0, PSZ("Unable to lock record"), ;
>>             PSZ("Record Lock Failure"), MB_RETRYCANCEL +
>> MB_ICONEXCLAMATION) != IDRETRY
>>             RETURN FALSE
>>         ENDIF
>>     ENDDO
>>     RETURN FALSE
>> FUNCTION OpenDbfQuiet(cFilename, cAliasname, lExclusive)
>>     LOCAL nTries := 0 AS INT
>>
>>     EnterCriticalSection(@CS_WATCHERR)
>>     IF IsNil(lExclusive)
>>         lExclusive := FALSE
>>     ENDIF
>>     IF IsNil(cAliasname)
>>         cAliasname := cFilename
>>     ENDIF
>>     IF SELECT(cAliasname) != 0    // Alias already in use
>>         cAliasname := Symbol2String(ConstructUniqueAlias(cFilename))
>>     ENDIF
>>
>>     WHILE nTries < 10
>>         ++nTries
>>         DBUSEAREA(TRUE, "DBFCDX", cFilename, cAliasname, !lExclusive,
>> FALSE)
>>         IF !NetErr()
>>             LeaveCriticalSection(@CS_WATCHERR)
>>             RETURN TRUE
>>         ENDIF
>>         Sleep(50)
>>     END
>>     LeaveCriticalSection(@CS_WATCHERR)
>>     RETURN FALSE
>>
>> Ginny
>>
>> "Martin"  wrote in message news:QGkwt.122934$G56.87814@fx32.fr7...
>>
>> Very interesting, you are using direct DBF rather than servers, I will
>> try that thankyou
>>
>> On 19/06/2013 15:02, Ginny Caughey wrote:
>>> Martin,
>>>
>>> I'm really not seeing anything obviously wrong here. Have you tried it
>>> without the Dynlock/Dynunlock? Here's my threaded code that ran without
>>> issues for several years. Maybe you'll spot something useful:
>>>
>>> FUNCTION RunPollingLoop( pInfo AS WatchInfo ) AS DWORD PASCAL    //
>>> Threaded function
>>>     LOCAL uMsg IS _winMsg    // used by thread message loop
>>>     LOCAL aParity AS ARRAY
>>>     LOCAL i AS INT
>>>     LOCAL cScale, cParity AS STRING
>>>     LOCAL nWeight, nTopWeight, nMinimumWt, nDelay AS INT
>>>     LOCAL dwStop AS DWORD
>>>     LOCAL dDate AS DATE
>>>     LOCAL cTime AS STRING
>>>     LOCAL oReader AS ScaleWatcher    // object that actually reads the
>>> scale and performs NTEP weight validation
>>>     LOCAL control, watchman, wconfig AS DWORD    // workareas for dbf
>>> files
>>>     LOCAL lError AS LOGIC
>>>
>>>     // Update status bar with scale started text
>>>     PostMessage(pInfo.hWnd, MSG_StartStop, pInfo.ScaleNumber,
>>> ScaleStarted)
>>>
>>>     // read paramters for this scale from wconfig and control files
>>>     aParity := { {"E", EvenParity}, ;
>>>                 {"M", MarkParity}, ;
>>>                 {"N", NoParity}, ;
>>>                 {"O", OddParity}, ;
>>>                 {"S", SpaceParity}     }
>>>
>>>     BEGIN SEQUENCE
>>>         IF !OpenDbfQuiet("control")
>>>             BREAK
>>>         ENDIF
>>>         control := DBGETSELECT()
>>>         IF !OpenDbfQuiet("wconfig")
>>>             BREAK
>>>         ENDIF
>>>         wconfig := DBGETSELECT()
>>>         IF !OpenDbfQuiet("watchman")
>>>             BREAK
>>>         ENDIF
>>>         watchman := DBGETSELECT()
>>>     RECOVER
>>>         lError := TRUE
>>>         HandleError("Unable to open a file needed to run Watchman Mode
>>> processing.")
>>>         IF control > 0
>>>             DBSELECTAREA(control)
>>>             DBCLOSEAREA()
>>>         ENDIF
>>>         IF wconfig > 0
>>>             DBSELECTAREA(wconfig)
>>>             DBCLOSEAREA()
>>>         ENDIF
>>>         IF watchman > 0
>>>             DBSELECTAREA(watchman)
>>>             DBCLOSEAREA()
>>>         ENDIF
>>>     END SEQUENCE
>>>
>>>     IF lError
>>>         RETURN 0
>>>     ENDIF
>>>
>>>     PostMessage(pInfo.hWnd, MSG_GettingData, pInfo.ScaleNumber, 0)
>>>     oReader := ScaleWatcher{pInfo.hWnd}
>>>     oReader:CommPort := "Com"+ NTrim(pInfo.PortNumber)
>>>     Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Getting info for
>>> scale")
>>>
>>>     // Get info for this scale port from control file
>>>     cScale := Str(pInfo.ScaleNumber,1,0)
>>>     nMinimumWt := (wconfig)->minimumwt
>>>     nDelay := (wconfig)->interval
>>>     (wconfig)->(DBCLOSEAREA())
>>>
>>>     oReader:Baud := (control)->(FIELDGET(FieldPos("baud"+cScale)))
>>>     oReader:Databits :=
>>> (control)->(FIELDGET(FieldPos("databits"+cScale)))
>>>     oReader:Stopbits :=
>>> (control)->(FIELDGET(FieldPos("stopbits"+cScale)))
>>>     IF oReader:Stopbits = 1
>>>         oReader:Stopbits := OneStopBit    // convert to Windows value (2
>>> = TwoStopBits already)
>>>     ENDIF
>>>     cParity := (control)->(FIELDGET(FieldPos("parity"+cScale)))
>>>     i := AScan(aParity, {|aVal| aVal[1] = cParity})
>>>     IF i > 0
>>>         oReader:Parity := aParity[i,2]
>>>     ELSE
>>>         oReader:Parity := NoParity
>>>     ENDIF
>>>     oReader:Buffsize :=
>>> (control)->(FIELDGET(FieldPos("buffsize"+cScale)))
>>>     oReader:WtBegin := (control)->(FIELDGET(FieldPos("wtbegin"+cScale)))
>>>     oReader:WtLength :=
>>> (control)->(FIELDGET(FieldPos("wtlength"+cScale)))
>>>     oReader:CheckChar :=
>>> (control)->(FIELDGET(FieldPos("poll1chr"+cScale)))
>>>     oReader:CheckPosition :=
>>> (control)->(FIELDGET(FieldPos("poll2chr"+cScale)))
>>>     oReader:MaxRetries :=
>>> (control)->(FIELDGET(FieldPos("poll3chr"+cScale)))
>>>     oReader:MotionChar :=
>>> (control)->(FIELDGET(FieldPos("poll4chr"+cScale)))
>>>     oReader:MotionByte := (control)->(FIELDGET(FieldPos("ack"+cScale)))
>>>     oReader:GrossLoc :=
>>> (control)->(FIELDGET(FieldPos("grossloc"+cScale)))
>>>     oReader:UnitLoc := (control)->(FIELDGET(FieldPos("unitloc"+cScale)))
>>>     oReader:ScaleUnit := (control)->(FIELDGET(FieldPos("scaleunit")))
>>>     (control)->(DBCLOSEAREA())
>>>
>>>     // Run polling loop until WM_QUIT received from primary thread
>>>     // Polling is a two step process here:
>>>     //    1. Sample every nDelay seconds for a weigh large enough to
>>> indicate a vehicle
>>>     //    2. Once a vehicle is on the scale, sample at 1/10 second
>>> intervals to catch maximum weight
>>>     WHILE TRUE
>>>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - In polling loop")
>>>         //PostMessage(pInfo.hWnd, MSG_Polling, pInfo.ScaleNumber, 0)
>>>         IF PeekMessage(@uMsg, 0, 0, 0, PM_REMOVE)    // PeekMessage
>>> returns true if any messages in queue
>>>             IF uMsg.message == WM_QUIT
>>>                 EXIT
>>>             ENDIF
>>>         ENDIF
>>>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Getting first
>>> weight")
>>>         nWeight := oReader:ReadScale()
>>>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - nWeight is
>>> "+NTrim(nWeight))
>>>         IF oReader:CancelRequested
>>>             EXIT
>>>         ENDIF
>>>         IF nWeight = -1    // Error occurred
>>>             PostMessage(pInfo.hWnd, MSG_ScaleError, pInfo.ScaleNumber, 
>>> 0)
>>>         ELSEIF nWeight < nMinimumWt
>>>             dwStop := GetTickCountLow()+DWORD(nDelay * 1000)
>>>             //PostMessage(pInfo.hWnd, MSG_Polling, pInfo.ScaleNumber, 0)
>>>             WHILE GetTickCountLow() <= dwStop
>>>                 IF PeekMessage(@uMsg, 0, 0, 0, PM_REMOVE)
>>>                     IF uMsg.message == WM_QUIT
>>>                         EXIT
>>>                     ENDIF
>>>                 ENDIF
>>>             END
>>>         ELSE
>>>             // We have a vehicle on scale
>>>             // Sample every 1/10 second until its maximum weight is
>>> captured
>>>             PostMessage(pInfo.hWnd, MSG_Sampling, pInfo.ScaleNumber, 0)
>>>             nTopWeight := nWeight
>>>             dDate := Today()
>>>             cTime := Time24()
>>>             WHILE TRUE
>>>                 IF PeekMessage(@uMsg, 0, 0, 0, PM_NOREMOVE)
>>>                     IF uMsg.message == WM_QUIT
>>>                         EXIT
>>>                     ENDIF
>>>                 ENDIF
>>>                 Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Testing
>>> for maximum weight")
>>>                 nWeight := oReader:ReadScale()
>>>                 IF oReader:CancelRequested
>>>                     EXIT
>>>                 ENDIF
>>>                 IF nWeight < nMinimumWt .AND. !oReader:MotionDetected
>>>                     EXIT
>>>                 ENDIF
>>>                 IF nWeight > nTopWeight
>>>                     nTopWeight := nWeight
>>>                     dDate := Today()
>>>                     cTime := Time24()
>>>                 ENDIF
>>>                 Sleep(100)    // give time slice to other threads for
>>> 1/10 second
>>>             END
>>>             IF uMsg.message != WM_QUIT .AND. !oReader:CancelRequested
>>>                 // Write out weight to file using file sharing
>>>                 IF (watchman)->(AddDbfQuiet())
>>>                     (watchman)->today := dDate
>>>                     (watchman)->time24 := cTime
>>>                     (watchman)->weight := nTopWeight
>>>                     (watchman)->scaleno := Str(pInfo.ScaleNumber,1,0)
>>>                     (watchman)->(DBCOMMIT())
>>>                     (watchman)->(DBUNLOCK())
>>>                 ELSE
>>>                     HandleError("Unable to add a record to the watchman
>>> file.")
>>>                 ENDIF
>>>             ELSE
>>>                 EXIT
>>>             ENDIF
>>>         ENDIF
>>>         IF uMsg.message == WM_QUIT .OR. oReader:CancelRequested
>>>             EXIT
>>>         ENDIF
>>>     END
>>>     Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Shutting down 
>>> thread")
>>>     (watchman)->(DBCLOSEAREA())
>>>     RETURN 0
>>> FUNCTION Output( s AS STRING ) AS VOID PASCAL    // thread-safe way to
>>> write to log file
>>>     IF hDebug != NULL_PTR
>>>         EnterCriticalSection(@CS_DEBUG)
>>>         FWriteLine(hDebug, s)
>>>         LeaveCriticalSection(@CS_DEBUG)
>>>     ENDIF
>>>     RETURN
>>> FUNCTION HandleError(cError AS STRING) AS VOID PASCAL
>>>     LOCAL hFile AS PTR
>>>
>>>     // Thread-safe write to log file
>>>     EnterCriticalSection(@CS_WATCHERR)
>>>     IF File(GetDefault()+"watcherr.log")
>>>         hFile := FOpen(GetDefault()+"watcherr.log", FO_READWRITE)
>>>         FSeek(hFile, 0, FS_END)
>>>     ELSE
>>>         hFile := FCreate(GetDefault()+"watcherr.log")
>>>     ENDIF
>>>     IF hFile != F_ERROR
>>>         FWrite(hFile, DToC(Today())+" "+Time24()+"
>>> "+cError+_CHR(13)+_CHR(10))
>>>         FClose(hFile)
>>>     ENDIF
>>>     LeaveCriticalSection(@CS_WATCHERR)
>>> Ginny
>>>
>>> "Martin"  wrote in message news:vMgwt.107261$4C2.78184@fx23.fr7...
>>>
>>> Here we go Ginny
>>>
>>>
>>> Thanks
>>>
>>> Martin
>>>
>

[toc] | [prev] | [next] | [standalone]


#5396

FromMartin <spam@spam.spam>
Date2013-06-21 15:39 +0100
Message-ID<iAZwt.151870$xc1.67522@fx06.fr7>
In reply to#5395
Postmessage between applications - need to read up on that, just what I need

On 21/06/2013 11:54, Ginny Caughey wrote:
> I really think you'll be happier with that approach. Multithreading can
> work in VO with DBF access, but it's tricky. The communication between
> windows using PostMessage used inside a multithreaded app can also be
> used across apps, so there's no real advantage to having everything in
> one app.
>
> Ginny
>
> "Martin (BT)"  wrote in message
> news:z5idnQZjZaab9V7MnZ2dnUVZ8uSdnZ2d@bt.com...
>
> I think I will have to go down the seperate .exe route, not good, but I
> have
> linked in a few thousand lines of library code.
>
>
> "Ginny Caughey" <gcaughey@online.hotmail.com> wrote in message
> news:51c34422$0$57923$c3e8da3$eb767761@news.astraweb.com...
>> If your UI thread is accessing DBF files without using the same DBF
>> functions as the worker thread, that could be the issue.
>>
>> Ginny
>>
>> "Martin"  wrote in message news:ARFwt.114422$P_4.83439@fx31.fr7...
>>
>> Thanks Ginny
>>
>> Just been testing since we have got the server running (blew up after
>> power cut despite UPS), with thread running the scanning code (main
>> .exe) crashes accessing the barcode system. thread carries on running
>> until I quit.
>>
>> Not using servers in thread, but Clipper style, any access controlled
>> with critical sections
>>
>> Note the same type of error in two files, both are open in the thread
>> with their own opens.
>>
>> Arg:             uField
>> ArgNum:          0
>> Args:          1 BC_ORDER : SYMBOL
>> ArgType:         NIL
>> ArgTypeReq:      NIL
>> CallFuncSym:     FIELDGET
>> CanDefault:      .F.
>> CanRetry:        .F.
>> CanSubstitute:   .F.
>> Description:     Wrong field specification
>>
>>
>>
>> Error Detail
>> Arg:             uField
>> ArgNum:          0
>> Args:          1 PL_DATE : SYMBOL
>> ArgType:         NIL
>> ArgTypeReq:      NIL
>> CallFuncSym:     FIELDGET
>> CanDefault:      .F.
>> CanRetry:        .F.
>> CanSubstitute:   .F.
>> Description:     Wrong field specification
>> FileHandle:      0
>> FileName:
>> FuncPtr:         0x00000000
>> FuncSym:         FIELDGET
>> GenCode:         1 : Argument error
>> MaxSize:         0
>> MethodSelf:      BarList
>> Operation:
>> OsCode:          0 : Successful completion
>> Severity:        ERROR
>> SubCode:         0
>> SubCodeText:
>> SubstituteType:  NIL
>> SubSystem:       Database
>> Tries:           0
>>
>>
>>
>>
>> On 20/06/2013 12:22, Ginny Caughey wrote:
>>> Here are the wrapper functions I'm using:
>>>
>>> FUNCTION AddDbf()
>>>     LOCAL dwStop AS DWORD
>>>
>>>     WHILE TRUE
>>>         dwStop := GetTickCountLow()+5000
>>>         WHILE GetTickCountLow() < dwStop
>>>                DBAPPEND()
>>>                IF ! NetErr()
>>>                   RETURN TRUE
>>>                ENDIF
>>>                Sleep(100)
>>>         ENDDO
>>>         IF MessageBox(0, PSZ("Unable to add a record to file"), ;
>>>             PSZ("Append Failure"), MB_RETRYCANCEL + MB_ICONEXCLAMATION)
>>> != IDRETRY
>>>             EXIT
>>>         ENDIF
>>>     END
>>>     RETURN FALSE
>>> STATIC FUNCTION ConstructUniqueAlias( cFileName AS STRING ) AS SYMBOL
>>> PASCAL
>>>     // Borrowed from 1.0c SDK in dbfsrvr.prg
>>>     LOCAL cTryNewAlias AS STRING
>>>     LOCAL w AS DWORD
>>>
>>>     IF IsNil(cFileName)
>>>         cFileName := "NOFILENAME"
>>>     ELSEIF ( w := At( ".", cFileName ) )>0
>>>         cFileName := SubStr( cFileName, 1, w-1 )
>>>     ENDIF
>>>     w := 1
>>>     cTryNewAlias := Upper(cFileName)
>>>
>>>     DO WHILE VODBSymSelect( String2Symbol( cTryNewAlias ) )>0
>>>         cTryNewAlias := Upper(cFileName)+"_"+AllTrim( Str( w++ ) )
>>>     ENDDO
>>>
>>>     RETURN String2Symbol(cTryNewAlias)
>>> FUNCTION XOpenDBF(cFilename)
>>>     RETURN OpenDbf(cFilename, , TRUE)
>>> FUNCTION OpenDbf(cFilename, cAliasname, lExclusive)
>>>     LOCAL dwStop AS DWORD
>>>     LOCAL lRet AS LOGIC
>>>
>>>     IF IsNil(lExclusive)
>>>         lExclusive := FALSE
>>>     ENDIF
>>>     IF IsNil(cAliasname)
>>>         cAliasname := cFilename
>>>     ENDIF
>>>     IF SELECT(cAliasname) != 0    // Alias already in use
>>>         cAliasname := Symbol2String(ConstructUniqueAlias(cFilename))
>>>     ENDIF
>>>     BEGIN SEQUENCE
>>>         WHILE TRUE
>>>             dwStop := GetTickCountLow()+5000 // allow .5 sec. retry
>>>             WHILE GetTickCountLow() <= dwStop
>>>                 Sleep(100)
>>>                 DBUSEAREA(TRUE, , cFilename, cAliasname, !lExclusive,
>>> FALSE)
>>>                 // use (cFilename) ALIAS (cAliasname) shared new
>>>                 IF ! NetErr()
>>>                     lRet := TRUE
>>>                     BREAK
>>>                 ENDIF
>>>             END
>>>             IF MessageBox(0, PSZ("Unable to open file "+cFilename), ;
>>>                 PSZ("File Open Error"), MB_RETRYCANCEL +
>>> MB_ICONEXCLAMATION) != IDRETRY
>>>                 EXIT
>>>             ENDIF
>>>         ENDDO
>>>     END SEQUENCE
>>>     IF lRet
>>>         cFilename := Upper(cFilename)
>>>         DO CASE
>>>             CASE cFilename = "RATECODE"
>>>                 DBFIELDINFO(DBS_ALIAS, FieldPos("code"), "_code")
>>>             CASE cFilename = "TICKET"
>>>                 DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
>>>             CASE cFilename = "INVOICE"
>>>                 DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
>>>             CASE cFilename = "HISTORY"
>>>                 DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
>>>         ENDCASE
>>>     ENDIF
>>>     RETURN lRet
>>> FUNCTION AddDbfQuiet()
>>>     LOCAL nTries := 0 AS INT
>>>
>>>     EnterCriticalSection(@CS_WATCHERR)
>>>     WHILE nTries < 10
>>>
>>>            DBAPPEND(TRUE)
>>>            IF !NetErr()
>>>                LeaveCriticalSection(@CS_WATCHERR)
>>>               RETURN TRUE
>>>            ENDIF
>>>            ++nTries
>>>            Sleep(50)
>>>     ENDDO
>>>     LeaveCriticalSection(@CS_WATCHERR)
>>>     RETURN FALSE
>>> FUNCTION EditDbf()
>>>     LOCAL nTries := 0 AS INT
>>>
>>>     WHILE nTries < 10
>>>         ++nTries
>>>         //IF DBRLOCK(RECNO())
>>>         IF DBRLOCK()
>>>             RETURN TRUE
>>>         ENDIF
>>>         IF nTries < 5
>>>             Sleep(100)
>>>             LOOP
>>>         ENDIF
>>>         IF MessageBox(0, PSZ("Unable to lock record"), ;
>>>             PSZ("Record Lock Failure"), MB_RETRYCANCEL +
>>> MB_ICONEXCLAMATION) != IDRETRY
>>>             RETURN FALSE
>>>         ENDIF
>>>     ENDDO
>>>     RETURN FALSE
>>> FUNCTION OpenDbfQuiet(cFilename, cAliasname, lExclusive)
>>>     LOCAL nTries := 0 AS INT
>>>
>>>     EnterCriticalSection(@CS_WATCHERR)
>>>     IF IsNil(lExclusive)
>>>         lExclusive := FALSE
>>>     ENDIF
>>>     IF IsNil(cAliasname)
>>>         cAliasname := cFilename
>>>     ENDIF
>>>     IF SELECT(cAliasname) != 0    // Alias already in use
>>>         cAliasname := Symbol2String(ConstructUniqueAlias(cFilename))
>>>     ENDIF
>>>
>>>     WHILE nTries < 10
>>>         ++nTries
>>>         DBUSEAREA(TRUE, "DBFCDX", cFilename, cAliasname, !lExclusive,
>>> FALSE)
>>>         IF !NetErr()
>>>             LeaveCriticalSection(@CS_WATCHERR)
>>>             RETURN TRUE
>>>         ENDIF
>>>         Sleep(50)
>>>     END
>>>     LeaveCriticalSection(@CS_WATCHERR)
>>>     RETURN FALSE
>>>
>>> Ginny
>>>
>>> "Martin"  wrote in message news:QGkwt.122934$G56.87814@fx32.fr7...
>>>
>>> Very interesting, you are using direct DBF rather than servers, I will
>>> try that thankyou
>>>
>>> On 19/06/2013 15:02, Ginny Caughey wrote:
>>>> Martin,
>>>>
>>>> I'm really not seeing anything obviously wrong here. Have you tried it
>>>> without the Dynlock/Dynunlock? Here's my threaded code that ran without
>>>> issues for several years. Maybe you'll spot something useful:
>>>>
>>>> FUNCTION RunPollingLoop( pInfo AS WatchInfo ) AS DWORD PASCAL    //
>>>> Threaded function
>>>>     LOCAL uMsg IS _winMsg    // used by thread message loop
>>>>     LOCAL aParity AS ARRAY
>>>>     LOCAL i AS INT
>>>>     LOCAL cScale, cParity AS STRING
>>>>     LOCAL nWeight, nTopWeight, nMinimumWt, nDelay AS INT
>>>>     LOCAL dwStop AS DWORD
>>>>     LOCAL dDate AS DATE
>>>>     LOCAL cTime AS STRING
>>>>     LOCAL oReader AS ScaleWatcher    // object that actually reads the
>>>> scale and performs NTEP weight validation
>>>>     LOCAL control, watchman, wconfig AS DWORD    // workareas for dbf
>>>> files
>>>>     LOCAL lError AS LOGIC
>>>>
>>>>     // Update status bar with scale started text
>>>>     PostMessage(pInfo.hWnd, MSG_StartStop, pInfo.ScaleNumber,
>>>> ScaleStarted)
>>>>
>>>>     // read paramters for this scale from wconfig and control files
>>>>     aParity := { {"E", EvenParity}, ;
>>>>                 {"M", MarkParity}, ;
>>>>                 {"N", NoParity}, ;
>>>>                 {"O", OddParity}, ;
>>>>                 {"S", SpaceParity}     }
>>>>
>>>>     BEGIN SEQUENCE
>>>>         IF !OpenDbfQuiet("control")
>>>>             BREAK
>>>>         ENDIF
>>>>         control := DBGETSELECT()
>>>>         IF !OpenDbfQuiet("wconfig")
>>>>             BREAK
>>>>         ENDIF
>>>>         wconfig := DBGETSELECT()
>>>>         IF !OpenDbfQuiet("watchman")
>>>>             BREAK
>>>>         ENDIF
>>>>         watchman := DBGETSELECT()
>>>>     RECOVER
>>>>         lError := TRUE
>>>>         HandleError("Unable to open a file needed to run Watchman Mode
>>>> processing.")
>>>>         IF control > 0
>>>>             DBSELECTAREA(control)
>>>>             DBCLOSEAREA()
>>>>         ENDIF
>>>>         IF wconfig > 0
>>>>             DBSELECTAREA(wconfig)
>>>>             DBCLOSEAREA()
>>>>         ENDIF
>>>>         IF watchman > 0
>>>>             DBSELECTAREA(watchman)
>>>>             DBCLOSEAREA()
>>>>         ENDIF
>>>>     END SEQUENCE
>>>>
>>>>     IF lError
>>>>         RETURN 0
>>>>     ENDIF
>>>>
>>>>     PostMessage(pInfo.hWnd, MSG_GettingData, pInfo.ScaleNumber, 0)
>>>>     oReader := ScaleWatcher{pInfo.hWnd}
>>>>     oReader:CommPort := "Com"+ NTrim(pInfo.PortNumber)
>>>>     Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Getting info for
>>>> scale")
>>>>
>>>>     // Get info for this scale port from control file
>>>>     cScale := Str(pInfo.ScaleNumber,1,0)
>>>>     nMinimumWt := (wconfig)->minimumwt
>>>>     nDelay := (wconfig)->interval
>>>>     (wconfig)->(DBCLOSEAREA())
>>>>
>>>>     oReader:Baud := (control)->(FIELDGET(FieldPos("baud"+cScale)))
>>>>     oReader:Databits :=
>>>> (control)->(FIELDGET(FieldPos("databits"+cScale)))
>>>>     oReader:Stopbits :=
>>>> (control)->(FIELDGET(FieldPos("stopbits"+cScale)))
>>>>     IF oReader:Stopbits = 1
>>>>         oReader:Stopbits := OneStopBit    // convert to Windows
>>>> value (2
>>>> = TwoStopBits already)
>>>>     ENDIF
>>>>     cParity := (control)->(FIELDGET(FieldPos("parity"+cScale)))
>>>>     i := AScan(aParity, {|aVal| aVal[1] = cParity})
>>>>     IF i > 0
>>>>         oReader:Parity := aParity[i,2]
>>>>     ELSE
>>>>         oReader:Parity := NoParity
>>>>     ENDIF
>>>>     oReader:Buffsize :=
>>>> (control)->(FIELDGET(FieldPos("buffsize"+cScale)))
>>>>     oReader:WtBegin :=
>>>> (control)->(FIELDGET(FieldPos("wtbegin"+cScale)))
>>>>     oReader:WtLength :=
>>>> (control)->(FIELDGET(FieldPos("wtlength"+cScale)))
>>>>     oReader:CheckChar :=
>>>> (control)->(FIELDGET(FieldPos("poll1chr"+cScale)))
>>>>     oReader:CheckPosition :=
>>>> (control)->(FIELDGET(FieldPos("poll2chr"+cScale)))
>>>>     oReader:MaxRetries :=
>>>> (control)->(FIELDGET(FieldPos("poll3chr"+cScale)))
>>>>     oReader:MotionChar :=
>>>> (control)->(FIELDGET(FieldPos("poll4chr"+cScale)))
>>>>     oReader:MotionByte := (control)->(FIELDGET(FieldPos("ack"+cScale)))
>>>>     oReader:GrossLoc :=
>>>> (control)->(FIELDGET(FieldPos("grossloc"+cScale)))
>>>>     oReader:UnitLoc :=
>>>> (control)->(FIELDGET(FieldPos("unitloc"+cScale)))
>>>>     oReader:ScaleUnit := (control)->(FIELDGET(FieldPos("scaleunit")))
>>>>     (control)->(DBCLOSEAREA())
>>>>
>>>>     // Run polling loop until WM_QUIT received from primary thread
>>>>     // Polling is a two step process here:
>>>>     //    1. Sample every nDelay seconds for a weigh large enough to
>>>> indicate a vehicle
>>>>     //    2. Once a vehicle is on the scale, sample at 1/10 second
>>>> intervals to catch maximum weight
>>>>     WHILE TRUE
>>>>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - In polling
>>>> loop")
>>>>         //PostMessage(pInfo.hWnd, MSG_Polling, pInfo.ScaleNumber, 0)
>>>>         IF PeekMessage(@uMsg, 0, 0, 0, PM_REMOVE)    // PeekMessage
>>>> returns true if any messages in queue
>>>>             IF uMsg.message == WM_QUIT
>>>>                 EXIT
>>>>             ENDIF
>>>>         ENDIF
>>>>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Getting first
>>>> weight")
>>>>         nWeight := oReader:ReadScale()
>>>>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - nWeight is
>>>> "+NTrim(nWeight))
>>>>         IF oReader:CancelRequested
>>>>             EXIT
>>>>         ENDIF
>>>>         IF nWeight = -1    // Error occurred
>>>>             PostMessage(pInfo.hWnd, MSG_ScaleError,
>>>> pInfo.ScaleNumber, 0)
>>>>         ELSEIF nWeight < nMinimumWt
>>>>             dwStop := GetTickCountLow()+DWORD(nDelay * 1000)
>>>>             //PostMessage(pInfo.hWnd, MSG_Polling,
>>>> pInfo.ScaleNumber, 0)
>>>>             WHILE GetTickCountLow() <= dwStop
>>>>                 IF PeekMessage(@uMsg, 0, 0, 0, PM_REMOVE)
>>>>                     IF uMsg.message == WM_QUIT
>>>>                         EXIT
>>>>                     ENDIF
>>>>                 ENDIF
>>>>             END
>>>>         ELSE
>>>>             // We have a vehicle on scale
>>>>             // Sample every 1/10 second until its maximum weight is
>>>> captured
>>>>             PostMessage(pInfo.hWnd, MSG_Sampling, pInfo.ScaleNumber, 0)
>>>>             nTopWeight := nWeight
>>>>             dDate := Today()
>>>>             cTime := Time24()
>>>>             WHILE TRUE
>>>>                 IF PeekMessage(@uMsg, 0, 0, 0, PM_NOREMOVE)
>>>>                     IF uMsg.message == WM_QUIT
>>>>                         EXIT
>>>>                     ENDIF
>>>>                 ENDIF
>>>>                 Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Testing
>>>> for maximum weight")
>>>>                 nWeight := oReader:ReadScale()
>>>>                 IF oReader:CancelRequested
>>>>                     EXIT
>>>>                 ENDIF
>>>>                 IF nWeight < nMinimumWt .AND. !oReader:MotionDetected
>>>>                     EXIT
>>>>                 ENDIF
>>>>                 IF nWeight > nTopWeight
>>>>                     nTopWeight := nWeight
>>>>                     dDate := Today()
>>>>                     cTime := Time24()
>>>>                 ENDIF
>>>>                 Sleep(100)    // give time slice to other threads for
>>>> 1/10 second
>>>>             END
>>>>             IF uMsg.message != WM_QUIT .AND. !oReader:CancelRequested
>>>>                 // Write out weight to file using file sharing
>>>>                 IF (watchman)->(AddDbfQuiet())
>>>>                     (watchman)->today := dDate
>>>>                     (watchman)->time24 := cTime
>>>>                     (watchman)->weight := nTopWeight
>>>>                     (watchman)->scaleno := Str(pInfo.ScaleNumber,1,0)
>>>>                     (watchman)->(DBCOMMIT())
>>>>                     (watchman)->(DBUNLOCK())
>>>>                 ELSE
>>>>                     HandleError("Unable to add a record to the watchman
>>>> file.")
>>>>                 ENDIF
>>>>             ELSE
>>>>                 EXIT
>>>>             ENDIF
>>>>         ENDIF
>>>>         IF uMsg.message == WM_QUIT .OR. oReader:CancelRequested
>>>>             EXIT
>>>>         ENDIF
>>>>     END
>>>>     Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Shutting down
>>>> thread")
>>>>     (watchman)->(DBCLOSEAREA())
>>>>     RETURN 0
>>>> FUNCTION Output( s AS STRING ) AS VOID PASCAL    // thread-safe way to
>>>> write to log file
>>>>     IF hDebug != NULL_PTR
>>>>         EnterCriticalSection(@CS_DEBUG)
>>>>         FWriteLine(hDebug, s)
>>>>         LeaveCriticalSection(@CS_DEBUG)
>>>>     ENDIF
>>>>     RETURN
>>>> FUNCTION HandleError(cError AS STRING) AS VOID PASCAL
>>>>     LOCAL hFile AS PTR
>>>>
>>>>     // Thread-safe write to log file
>>>>     EnterCriticalSection(@CS_WATCHERR)
>>>>     IF File(GetDefault()+"watcherr.log")
>>>>         hFile := FOpen(GetDefault()+"watcherr.log", FO_READWRITE)
>>>>         FSeek(hFile, 0, FS_END)
>>>>     ELSE
>>>>         hFile := FCreate(GetDefault()+"watcherr.log")
>>>>     ENDIF
>>>>     IF hFile != F_ERROR
>>>>         FWrite(hFile, DToC(Today())+" "+Time24()+"
>>>> "+cError+_CHR(13)+_CHR(10))
>>>>         FClose(hFile)
>>>>     ENDIF
>>>>     LeaveCriticalSection(@CS_WATCHERR)
>>>> Ginny
>>>>
>>>> "Martin"  wrote in message news:vMgwt.107261$4C2.78184@fx23.fr7...
>>>>
>>>> Here we go Ginny
>>>>
>>>>
>>>> Thanks
>>>>
>>>> Martin
>>>>
>>
>

[toc] | [prev] | [next] | [standalone]


#5397

FromMartin <spam@spam.spam>
Date2013-06-21 15:54 +0100
Message-ID<IOZwt.96404$Ii.66384@fx19.fr7>
In reply to#5396
FindWindow - now how do I make it work by class?

On 21/06/2013 15:39, Martin wrote:
> Postmessage between applications - need to read up on that, just what I
> need
>
> On 21/06/2013 11:54, Ginny Caughey wrote:
>> I really think you'll be happier with that approach. Multithreading can
>> work in VO with DBF access, but it's tricky. The communication between
>> windows using PostMessage used inside a multithreaded app can also be
>> used across apps, so there's no real advantage to having everything in
>> one app.
>>
>> Ginny
>>
>> "Martin (BT)"  wrote in message
>> news:z5idnQZjZaab9V7MnZ2dnUVZ8uSdnZ2d@bt.com...
>>
>> I think I will have to go down the seperate .exe route, not good, but I
>> have
>> linked in a few thousand lines of library code.
>>
>>
>> "Ginny Caughey" <gcaughey@online.hotmail.com> wrote in message
>> news:51c34422$0$57923$c3e8da3$eb767761@news.astraweb.com...
>>> If your UI thread is accessing DBF files without using the same DBF
>>> functions as the worker thread, that could be the issue.
>>>
>>> Ginny
>>>
>>> "Martin"  wrote in message news:ARFwt.114422$P_4.83439@fx31.fr7...
>>>
>>> Thanks Ginny
>>>
>>> Just been testing since we have got the server running (blew up after
>>> power cut despite UPS), with thread running the scanning code (main
>>> .exe) crashes accessing the barcode system. thread carries on running
>>> until I quit.
>>>
>>> Not using servers in thread, but Clipper style, any access controlled
>>> with critical sections
>>>
>>> Note the same type of error in two files, both are open in the thread
>>> with their own opens.
>>>
>>> Arg:             uField
>>> ArgNum:          0
>>> Args:          1 BC_ORDER : SYMBOL
>>> ArgType:         NIL
>>> ArgTypeReq:      NIL
>>> CallFuncSym:     FIELDGET
>>> CanDefault:      .F.
>>> CanRetry:        .F.
>>> CanSubstitute:   .F.
>>> Description:     Wrong field specification
>>>
>>>
>>>
>>> Error Detail
>>> Arg:             uField
>>> ArgNum:          0
>>> Args:          1 PL_DATE : SYMBOL
>>> ArgType:         NIL
>>> ArgTypeReq:      NIL
>>> CallFuncSym:     FIELDGET
>>> CanDefault:      .F.
>>> CanRetry:        .F.
>>> CanSubstitute:   .F.
>>> Description:     Wrong field specification
>>> FileHandle:      0
>>> FileName:
>>> FuncPtr:         0x00000000
>>> FuncSym:         FIELDGET
>>> GenCode:         1 : Argument error
>>> MaxSize:         0
>>> MethodSelf:      BarList
>>> Operation:
>>> OsCode:          0 : Successful completion
>>> Severity:        ERROR
>>> SubCode:         0
>>> SubCodeText:
>>> SubstituteType:  NIL
>>> SubSystem:       Database
>>> Tries:           0
>>>
>>>
>>>
>>>
>>> On 20/06/2013 12:22, Ginny Caughey wrote:
>>>> Here are the wrapper functions I'm using:
>>>>
>>>> FUNCTION AddDbf()
>>>>     LOCAL dwStop AS DWORD
>>>>
>>>>     WHILE TRUE
>>>>         dwStop := GetTickCountLow()+5000
>>>>         WHILE GetTickCountLow() < dwStop
>>>>                DBAPPEND()
>>>>                IF ! NetErr()
>>>>                   RETURN TRUE
>>>>                ENDIF
>>>>                Sleep(100)
>>>>         ENDDO
>>>>         IF MessageBox(0, PSZ("Unable to add a record to file"), ;
>>>>             PSZ("Append Failure"), MB_RETRYCANCEL + MB_ICONEXCLAMATION)
>>>> != IDRETRY
>>>>             EXIT
>>>>         ENDIF
>>>>     END
>>>>     RETURN FALSE
>>>> STATIC FUNCTION ConstructUniqueAlias( cFileName AS STRING ) AS SYMBOL
>>>> PASCAL
>>>>     // Borrowed from 1.0c SDK in dbfsrvr.prg
>>>>     LOCAL cTryNewAlias AS STRING
>>>>     LOCAL w AS DWORD
>>>>
>>>>     IF IsNil(cFileName)
>>>>         cFileName := "NOFILENAME"
>>>>     ELSEIF ( w := At( ".", cFileName ) )>0
>>>>         cFileName := SubStr( cFileName, 1, w-1 )
>>>>     ENDIF
>>>>     w := 1
>>>>     cTryNewAlias := Upper(cFileName)
>>>>
>>>>     DO WHILE VODBSymSelect( String2Symbol( cTryNewAlias ) )>0
>>>>         cTryNewAlias := Upper(cFileName)+"_"+AllTrim( Str( w++ ) )
>>>>     ENDDO
>>>>
>>>>     RETURN String2Symbol(cTryNewAlias)
>>>> FUNCTION XOpenDBF(cFilename)
>>>>     RETURN OpenDbf(cFilename, , TRUE)
>>>> FUNCTION OpenDbf(cFilename, cAliasname, lExclusive)
>>>>     LOCAL dwStop AS DWORD
>>>>     LOCAL lRet AS LOGIC
>>>>
>>>>     IF IsNil(lExclusive)
>>>>         lExclusive := FALSE
>>>>     ENDIF
>>>>     IF IsNil(cAliasname)
>>>>         cAliasname := cFilename
>>>>     ENDIF
>>>>     IF SELECT(cAliasname) != 0    // Alias already in use
>>>>         cAliasname := Symbol2String(ConstructUniqueAlias(cFilename))
>>>>     ENDIF
>>>>     BEGIN SEQUENCE
>>>>         WHILE TRUE
>>>>             dwStop := GetTickCountLow()+5000 // allow .5 sec. retry
>>>>             WHILE GetTickCountLow() <= dwStop
>>>>                 Sleep(100)
>>>>                 DBUSEAREA(TRUE, , cFilename, cAliasname, !lExclusive,
>>>> FALSE)
>>>>                 // use (cFilename) ALIAS (cAliasname) shared new
>>>>                 IF ! NetErr()
>>>>                     lRet := TRUE
>>>>                     BREAK
>>>>                 ENDIF
>>>>             END
>>>>             IF MessageBox(0, PSZ("Unable to open file "+cFilename), ;
>>>>                 PSZ("File Open Error"), MB_RETRYCANCEL +
>>>> MB_ICONEXCLAMATION) != IDRETRY
>>>>                 EXIT
>>>>             ENDIF
>>>>         ENDDO
>>>>     END SEQUENCE
>>>>     IF lRet
>>>>         cFilename := Upper(cFilename)
>>>>         DO CASE
>>>>             CASE cFilename = "RATECODE"
>>>>                 DBFIELDINFO(DBS_ALIAS, FieldPos("code"), "_code")
>>>>             CASE cFilename = "TICKET"
>>>>                 DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
>>>>             CASE cFilename = "INVOICE"
>>>>                 DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
>>>>             CASE cFilename = "HISTORY"
>>>>                 DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
>>>>         ENDCASE
>>>>     ENDIF
>>>>     RETURN lRet
>>>> FUNCTION AddDbfQuiet()
>>>>     LOCAL nTries := 0 AS INT
>>>>
>>>>     EnterCriticalSection(@CS_WATCHERR)
>>>>     WHILE nTries < 10
>>>>
>>>>            DBAPPEND(TRUE)
>>>>            IF !NetErr()
>>>>                LeaveCriticalSection(@CS_WATCHERR)
>>>>               RETURN TRUE
>>>>            ENDIF
>>>>            ++nTries
>>>>            Sleep(50)
>>>>     ENDDO
>>>>     LeaveCriticalSection(@CS_WATCHERR)
>>>>     RETURN FALSE
>>>> FUNCTION EditDbf()
>>>>     LOCAL nTries := 0 AS INT
>>>>
>>>>     WHILE nTries < 10
>>>>         ++nTries
>>>>         //IF DBRLOCK(RECNO())
>>>>         IF DBRLOCK()
>>>>             RETURN TRUE
>>>>         ENDIF
>>>>         IF nTries < 5
>>>>             Sleep(100)
>>>>             LOOP
>>>>         ENDIF
>>>>         IF MessageBox(0, PSZ("Unable to lock record"), ;
>>>>             PSZ("Record Lock Failure"), MB_RETRYCANCEL +
>>>> MB_ICONEXCLAMATION) != IDRETRY
>>>>             RETURN FALSE
>>>>         ENDIF
>>>>     ENDDO
>>>>     RETURN FALSE
>>>> FUNCTION OpenDbfQuiet(cFilename, cAliasname, lExclusive)
>>>>     LOCAL nTries := 0 AS INT
>>>>
>>>>     EnterCriticalSection(@CS_WATCHERR)
>>>>     IF IsNil(lExclusive)
>>>>         lExclusive := FALSE
>>>>     ENDIF
>>>>     IF IsNil(cAliasname)
>>>>         cAliasname := cFilename
>>>>     ENDIF
>>>>     IF SELECT(cAliasname) != 0    // Alias already in use
>>>>         cAliasname := Symbol2String(ConstructUniqueAlias(cFilename))
>>>>     ENDIF
>>>>
>>>>     WHILE nTries < 10
>>>>         ++nTries
>>>>         DBUSEAREA(TRUE, "DBFCDX", cFilename, cAliasname, !lExclusive,
>>>> FALSE)
>>>>         IF !NetErr()
>>>>             LeaveCriticalSection(@CS_WATCHERR)
>>>>             RETURN TRUE
>>>>         ENDIF
>>>>         Sleep(50)
>>>>     END
>>>>     LeaveCriticalSection(@CS_WATCHERR)
>>>>     RETURN FALSE
>>>>
>>>> Ginny
>>>>
>>>> "Martin"  wrote in message news:QGkwt.122934$G56.87814@fx32.fr7...
>>>>
>>>> Very interesting, you are using direct DBF rather than servers, I will
>>>> try that thankyou
>>>>
>>>> On 19/06/2013 15:02, Ginny Caughey wrote:
>>>>> Martin,
>>>>>
>>>>> I'm really not seeing anything obviously wrong here. Have you tried it
>>>>> without the Dynlock/Dynunlock? Here's my threaded code that ran
>>>>> without
>>>>> issues for several years. Maybe you'll spot something useful:
>>>>>
>>>>> FUNCTION RunPollingLoop( pInfo AS WatchInfo ) AS DWORD PASCAL    //
>>>>> Threaded function
>>>>>     LOCAL uMsg IS _winMsg    // used by thread message loop
>>>>>     LOCAL aParity AS ARRAY
>>>>>     LOCAL i AS INT
>>>>>     LOCAL cScale, cParity AS STRING
>>>>>     LOCAL nWeight, nTopWeight, nMinimumWt, nDelay AS INT
>>>>>     LOCAL dwStop AS DWORD
>>>>>     LOCAL dDate AS DATE
>>>>>     LOCAL cTime AS STRING
>>>>>     LOCAL oReader AS ScaleWatcher    // object that actually reads the
>>>>> scale and performs NTEP weight validation
>>>>>     LOCAL control, watchman, wconfig AS DWORD    // workareas for dbf
>>>>> files
>>>>>     LOCAL lError AS LOGIC
>>>>>
>>>>>     // Update status bar with scale started text
>>>>>     PostMessage(pInfo.hWnd, MSG_StartStop, pInfo.ScaleNumber,
>>>>> ScaleStarted)
>>>>>
>>>>>     // read paramters for this scale from wconfig and control files
>>>>>     aParity := { {"E", EvenParity}, ;
>>>>>                 {"M", MarkParity}, ;
>>>>>                 {"N", NoParity}, ;
>>>>>                 {"O", OddParity}, ;
>>>>>                 {"S", SpaceParity}     }
>>>>>
>>>>>     BEGIN SEQUENCE
>>>>>         IF !OpenDbfQuiet("control")
>>>>>             BREAK
>>>>>         ENDIF
>>>>>         control := DBGETSELECT()
>>>>>         IF !OpenDbfQuiet("wconfig")
>>>>>             BREAK
>>>>>         ENDIF
>>>>>         wconfig := DBGETSELECT()
>>>>>         IF !OpenDbfQuiet("watchman")
>>>>>             BREAK
>>>>>         ENDIF
>>>>>         watchman := DBGETSELECT()
>>>>>     RECOVER
>>>>>         lError := TRUE
>>>>>         HandleError("Unable to open a file needed to run Watchman Mode
>>>>> processing.")
>>>>>         IF control > 0
>>>>>             DBSELECTAREA(control)
>>>>>             DBCLOSEAREA()
>>>>>         ENDIF
>>>>>         IF wconfig > 0
>>>>>             DBSELECTAREA(wconfig)
>>>>>             DBCLOSEAREA()
>>>>>         ENDIF
>>>>>         IF watchman > 0
>>>>>             DBSELECTAREA(watchman)
>>>>>             DBCLOSEAREA()
>>>>>         ENDIF
>>>>>     END SEQUENCE
>>>>>
>>>>>     IF lError
>>>>>         RETURN 0
>>>>>     ENDIF
>>>>>
>>>>>     PostMessage(pInfo.hWnd, MSG_GettingData, pInfo.ScaleNumber, 0)
>>>>>     oReader := ScaleWatcher{pInfo.hWnd}
>>>>>     oReader:CommPort := "Com"+ NTrim(pInfo.PortNumber)
>>>>>     Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Getting info for
>>>>> scale")
>>>>>
>>>>>     // Get info for this scale port from control file
>>>>>     cScale := Str(pInfo.ScaleNumber,1,0)
>>>>>     nMinimumWt := (wconfig)->minimumwt
>>>>>     nDelay := (wconfig)->interval
>>>>>     (wconfig)->(DBCLOSEAREA())
>>>>>
>>>>>     oReader:Baud := (control)->(FIELDGET(FieldPos("baud"+cScale)))
>>>>>     oReader:Databits :=
>>>>> (control)->(FIELDGET(FieldPos("databits"+cScale)))
>>>>>     oReader:Stopbits :=
>>>>> (control)->(FIELDGET(FieldPos("stopbits"+cScale)))
>>>>>     IF oReader:Stopbits = 1
>>>>>         oReader:Stopbits := OneStopBit    // convert to Windows
>>>>> value (2
>>>>> = TwoStopBits already)
>>>>>     ENDIF
>>>>>     cParity := (control)->(FIELDGET(FieldPos("parity"+cScale)))
>>>>>     i := AScan(aParity, {|aVal| aVal[1] = cParity})
>>>>>     IF i > 0
>>>>>         oReader:Parity := aParity[i,2]
>>>>>     ELSE
>>>>>         oReader:Parity := NoParity
>>>>>     ENDIF
>>>>>     oReader:Buffsize :=
>>>>> (control)->(FIELDGET(FieldPos("buffsize"+cScale)))
>>>>>     oReader:WtBegin :=
>>>>> (control)->(FIELDGET(FieldPos("wtbegin"+cScale)))
>>>>>     oReader:WtLength :=
>>>>> (control)->(FIELDGET(FieldPos("wtlength"+cScale)))
>>>>>     oReader:CheckChar :=
>>>>> (control)->(FIELDGET(FieldPos("poll1chr"+cScale)))
>>>>>     oReader:CheckPosition :=
>>>>> (control)->(FIELDGET(FieldPos("poll2chr"+cScale)))
>>>>>     oReader:MaxRetries :=
>>>>> (control)->(FIELDGET(FieldPos("poll3chr"+cScale)))
>>>>>     oReader:MotionChar :=
>>>>> (control)->(FIELDGET(FieldPos("poll4chr"+cScale)))
>>>>>     oReader:MotionByte :=
>>>>> (control)->(FIELDGET(FieldPos("ack"+cScale)))
>>>>>     oReader:GrossLoc :=
>>>>> (control)->(FIELDGET(FieldPos("grossloc"+cScale)))
>>>>>     oReader:UnitLoc :=
>>>>> (control)->(FIELDGET(FieldPos("unitloc"+cScale)))
>>>>>     oReader:ScaleUnit := (control)->(FIELDGET(FieldPos("scaleunit")))
>>>>>     (control)->(DBCLOSEAREA())
>>>>>
>>>>>     // Run polling loop until WM_QUIT received from primary thread
>>>>>     // Polling is a two step process here:
>>>>>     //    1. Sample every nDelay seconds for a weigh large enough to
>>>>> indicate a vehicle
>>>>>     //    2. Once a vehicle is on the scale, sample at 1/10 second
>>>>> intervals to catch maximum weight
>>>>>     WHILE TRUE
>>>>>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - In polling
>>>>> loop")
>>>>>         //PostMessage(pInfo.hWnd, MSG_Polling, pInfo.ScaleNumber, 0)
>>>>>         IF PeekMessage(@uMsg, 0, 0, 0, PM_REMOVE)    // PeekMessage
>>>>> returns true if any messages in queue
>>>>>             IF uMsg.message == WM_QUIT
>>>>>                 EXIT
>>>>>             ENDIF
>>>>>         ENDIF
>>>>>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Getting first
>>>>> weight")
>>>>>         nWeight := oReader:ReadScale()
>>>>>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - nWeight is
>>>>> "+NTrim(nWeight))
>>>>>         IF oReader:CancelRequested
>>>>>             EXIT
>>>>>         ENDIF
>>>>>         IF nWeight = -1    // Error occurred
>>>>>             PostMessage(pInfo.hWnd, MSG_ScaleError,
>>>>> pInfo.ScaleNumber, 0)
>>>>>         ELSEIF nWeight < nMinimumWt
>>>>>             dwStop := GetTickCountLow()+DWORD(nDelay * 1000)
>>>>>             //PostMessage(pInfo.hWnd, MSG_Polling,
>>>>> pInfo.ScaleNumber, 0)
>>>>>             WHILE GetTickCountLow() <= dwStop
>>>>>                 IF PeekMessage(@uMsg, 0, 0, 0, PM_REMOVE)
>>>>>                     IF uMsg.message == WM_QUIT
>>>>>                         EXIT
>>>>>                     ENDIF
>>>>>                 ENDIF
>>>>>             END
>>>>>         ELSE
>>>>>             // We have a vehicle on scale
>>>>>             // Sample every 1/10 second until its maximum weight is
>>>>> captured
>>>>>             PostMessage(pInfo.hWnd, MSG_Sampling,
>>>>> pInfo.ScaleNumber, 0)
>>>>>             nTopWeight := nWeight
>>>>>             dDate := Today()
>>>>>             cTime := Time24()
>>>>>             WHILE TRUE
>>>>>                 IF PeekMessage(@uMsg, 0, 0, 0, PM_NOREMOVE)
>>>>>                     IF uMsg.message == WM_QUIT
>>>>>                         EXIT
>>>>>                     ENDIF
>>>>>                 ENDIF
>>>>>                 Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Testing
>>>>> for maximum weight")
>>>>>                 nWeight := oReader:ReadScale()
>>>>>                 IF oReader:CancelRequested
>>>>>                     EXIT
>>>>>                 ENDIF
>>>>>                 IF nWeight < nMinimumWt .AND. !oReader:MotionDetected
>>>>>                     EXIT
>>>>>                 ENDIF
>>>>>                 IF nWeight > nTopWeight
>>>>>                     nTopWeight := nWeight
>>>>>                     dDate := Today()
>>>>>                     cTime := Time24()
>>>>>                 ENDIF
>>>>>                 Sleep(100)    // give time slice to other threads for
>>>>> 1/10 second
>>>>>             END
>>>>>             IF uMsg.message != WM_QUIT .AND. !oReader:CancelRequested
>>>>>                 // Write out weight to file using file sharing
>>>>>                 IF (watchman)->(AddDbfQuiet())
>>>>>                     (watchman)->today := dDate
>>>>>                     (watchman)->time24 := cTime
>>>>>                     (watchman)->weight := nTopWeight
>>>>>                     (watchman)->scaleno := Str(pInfo.ScaleNumber,1,0)
>>>>>                     (watchman)->(DBCOMMIT())
>>>>>                     (watchman)->(DBUNLOCK())
>>>>>                 ELSE
>>>>>                     HandleError("Unable to add a record to the
>>>>> watchman
>>>>> file.")
>>>>>                 ENDIF
>>>>>             ELSE
>>>>>                 EXIT
>>>>>             ENDIF
>>>>>         ENDIF
>>>>>         IF uMsg.message == WM_QUIT .OR. oReader:CancelRequested
>>>>>             EXIT
>>>>>         ENDIF
>>>>>     END
>>>>>     Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Shutting down
>>>>> thread")
>>>>>     (watchman)->(DBCLOSEAREA())
>>>>>     RETURN 0
>>>>> FUNCTION Output( s AS STRING ) AS VOID PASCAL    // thread-safe way to
>>>>> write to log file
>>>>>     IF hDebug != NULL_PTR
>>>>>         EnterCriticalSection(@CS_DEBUG)
>>>>>         FWriteLine(hDebug, s)
>>>>>         LeaveCriticalSection(@CS_DEBUG)
>>>>>     ENDIF
>>>>>     RETURN
>>>>> FUNCTION HandleError(cError AS STRING) AS VOID PASCAL
>>>>>     LOCAL hFile AS PTR
>>>>>
>>>>>     // Thread-safe write to log file
>>>>>     EnterCriticalSection(@CS_WATCHERR)
>>>>>     IF File(GetDefault()+"watcherr.log")
>>>>>         hFile := FOpen(GetDefault()+"watcherr.log", FO_READWRITE)
>>>>>         FSeek(hFile, 0, FS_END)
>>>>>     ELSE
>>>>>         hFile := FCreate(GetDefault()+"watcherr.log")
>>>>>     ENDIF
>>>>>     IF hFile != F_ERROR
>>>>>         FWrite(hFile, DToC(Today())+" "+Time24()+"
>>>>> "+cError+_CHR(13)+_CHR(10))
>>>>>         FClose(hFile)
>>>>>     ENDIF
>>>>>     LeaveCriticalSection(@CS_WATCHERR)
>>>>> Ginny
>>>>>
>>>>> "Martin"  wrote in message news:vMgwt.107261$4C2.78184@fx23.fr7...
>>>>>
>>>>> Here we go Ginny
>>>>>
>>>>>
>>>>> Thanks
>>>>>
>>>>> Martin
>>>>>
>>>
>>
>

[toc] | [prev] | [next] | [standalone]


#5399

From"Ginny Caughey" <gcaughey@online.hotmail.com>
Date2013-06-21 12:12 -0400
Message-ID<51c47b67$0$59667$c3e8da3$66d3cc2f@news.astraweb.com>
In reply to#5397
Here's the gist of it: 
http://social.msdn.microsoft.com/Forums/windows/en-US/ccee7ae6-75ca-4916-89cf-a099d12074a7/send-message-to-other-process

This sample indicates you can pass null as the first parameter to 
FindWindow() and the windows title as the second: 
http://social.msdn.microsoft.com/Forums/en-US/18e41215-fc0f-4322-b942-4e1e90bafa48/c-findwindow

These samples use SendMessage, which is a blocking call, but you may prefer 
PostMessage, which isn't.

Ginny

"Martin"  wrote in message news:IOZwt.96404$Ii.66384@fx19.fr7...

FindWindow - now how do I make it work by class?

On 21/06/2013 15:39, Martin wrote:
> Postmessage between applications - need to read up on that, just what I
> need
>
> On 21/06/2013 11:54, Ginny Caughey wrote:
>> I really think you'll be happier with that approach. Multithreading can
>> work in VO with DBF access, but it's tricky. The communication between
>> windows using PostMessage used inside a multithreaded app can also be
>> used across apps, so there's no real advantage to having everything in
>> one app.
>>
>> Ginny
>>
>> "Martin (BT)"  wrote in message
>> news:z5idnQZjZaab9V7MnZ2dnUVZ8uSdnZ2d@bt.com...
>>
>> I think I will have to go down the seperate .exe route, not good, but I
>> have
>> linked in a few thousand lines of library code.
>>
>>
>> "Ginny Caughey" <gcaughey@online.hotmail.com> wrote in message
>> news:51c34422$0$57923$c3e8da3$eb767761@news.astraweb.com...
>>> If your UI thread is accessing DBF files without using the same DBF
>>> functions as the worker thread, that could be the issue.
>>>
>>> Ginny
>>>
>>> "Martin"  wrote in message news:ARFwt.114422$P_4.83439@fx31.fr7...
>>>
>>> Thanks Ginny
>>>
>>> Just been testing since we have got the server running (blew up after
>>> power cut despite UPS), with thread running the scanning code (main
>>> .exe) crashes accessing the barcode system. thread carries on running
>>> until I quit.
>>>
>>> Not using servers in thread, but Clipper style, any access controlled
>>> with critical sections
>>>
>>> Note the same type of error in two files, both are open in the thread
>>> with their own opens.
>>>
>>> Arg:             uField
>>> ArgNum:          0
>>> Args:          1 BC_ORDER : SYMBOL
>>> ArgType:         NIL
>>> ArgTypeReq:      NIL
>>> CallFuncSym:     FIELDGET
>>> CanDefault:      .F.
>>> CanRetry:        .F.
>>> CanSubstitute:   .F.
>>> Description:     Wrong field specification
>>>
>>>
>>>
>>> Error Detail
>>> Arg:             uField
>>> ArgNum:          0
>>> Args:          1 PL_DATE : SYMBOL
>>> ArgType:         NIL
>>> ArgTypeReq:      NIL
>>> CallFuncSym:     FIELDGET
>>> CanDefault:      .F.
>>> CanRetry:        .F.
>>> CanSubstitute:   .F.
>>> Description:     Wrong field specification
>>> FileHandle:      0
>>> FileName:
>>> FuncPtr:         0x00000000
>>> FuncSym:         FIELDGET
>>> GenCode:         1 : Argument error
>>> MaxSize:         0
>>> MethodSelf:      BarList
>>> Operation:
>>> OsCode:          0 : Successful completion
>>> Severity:        ERROR
>>> SubCode:         0
>>> SubCodeText:
>>> SubstituteType:  NIL
>>> SubSystem:       Database
>>> Tries:           0
>>>
>>>
>>>
>>>
>>> On 20/06/2013 12:22, Ginny Caughey wrote:
>>>> Here are the wrapper functions I'm using:
>>>>
>>>> FUNCTION AddDbf()
>>>>     LOCAL dwStop AS DWORD
>>>>
>>>>     WHILE TRUE
>>>>         dwStop := GetTickCountLow()+5000
>>>>         WHILE GetTickCountLow() < dwStop
>>>>                DBAPPEND()
>>>>                IF ! NetErr()
>>>>                   RETURN TRUE
>>>>                ENDIF
>>>>                Sleep(100)
>>>>         ENDDO
>>>>         IF MessageBox(0, PSZ("Unable to add a record to file"), ;
>>>>             PSZ("Append Failure"), MB_RETRYCANCEL + MB_ICONEXCLAMATION)
>>>> != IDRETRY
>>>>             EXIT
>>>>         ENDIF
>>>>     END
>>>>     RETURN FALSE
>>>> STATIC FUNCTION ConstructUniqueAlias( cFileName AS STRING ) AS SYMBOL
>>>> PASCAL
>>>>     // Borrowed from 1.0c SDK in dbfsrvr.prg
>>>>     LOCAL cTryNewAlias AS STRING
>>>>     LOCAL w AS DWORD
>>>>
>>>>     IF IsNil(cFileName)
>>>>         cFileName := "NOFILENAME"
>>>>     ELSEIF ( w := At( ".", cFileName ) )>0
>>>>         cFileName := SubStr( cFileName, 1, w-1 )
>>>>     ENDIF
>>>>     w := 1
>>>>     cTryNewAlias := Upper(cFileName)
>>>>
>>>>     DO WHILE VODBSymSelect( String2Symbol( cTryNewAlias ) )>0
>>>>         cTryNewAlias := Upper(cFileName)+"_"+AllTrim( Str( w++ ) )
>>>>     ENDDO
>>>>
>>>>     RETURN String2Symbol(cTryNewAlias)
>>>> FUNCTION XOpenDBF(cFilename)
>>>>     RETURN OpenDbf(cFilename, , TRUE)
>>>> FUNCTION OpenDbf(cFilename, cAliasname, lExclusive)
>>>>     LOCAL dwStop AS DWORD
>>>>     LOCAL lRet AS LOGIC
>>>>
>>>>     IF IsNil(lExclusive)
>>>>         lExclusive := FALSE
>>>>     ENDIF
>>>>     IF IsNil(cAliasname)
>>>>         cAliasname := cFilename
>>>>     ENDIF
>>>>     IF SELECT(cAliasname) != 0    // Alias already in use
>>>>         cAliasname := Symbol2String(ConstructUniqueAlias(cFilename))
>>>>     ENDIF
>>>>     BEGIN SEQUENCE
>>>>         WHILE TRUE
>>>>             dwStop := GetTickCountLow()+5000 // allow .5 sec. retry
>>>>             WHILE GetTickCountLow() <= dwStop
>>>>                 Sleep(100)
>>>>                 DBUSEAREA(TRUE, , cFilename, cAliasname, !lExclusive,
>>>> FALSE)
>>>>                 // use (cFilename) ALIAS (cAliasname) shared new
>>>>                 IF ! NetErr()
>>>>                     lRet := TRUE
>>>>                     BREAK
>>>>                 ENDIF
>>>>             END
>>>>             IF MessageBox(0, PSZ("Unable to open file "+cFilename), ;
>>>>                 PSZ("File Open Error"), MB_RETRYCANCEL +
>>>> MB_ICONEXCLAMATION) != IDRETRY
>>>>                 EXIT
>>>>             ENDIF
>>>>         ENDDO
>>>>     END SEQUENCE
>>>>     IF lRet
>>>>         cFilename := Upper(cFilename)
>>>>         DO CASE
>>>>             CASE cFilename = "RATECODE"
>>>>                 DBFIELDINFO(DBS_ALIAS, FieldPos("code"), "_code")
>>>>             CASE cFilename = "TICKET"
>>>>                 DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
>>>>             CASE cFilename = "INVOICE"
>>>>                 DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
>>>>             CASE cFilename = "HISTORY"
>>>>                 DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
>>>>         ENDCASE
>>>>     ENDIF
>>>>     RETURN lRet
>>>> FUNCTION AddDbfQuiet()
>>>>     LOCAL nTries := 0 AS INT
>>>>
>>>>     EnterCriticalSection(@CS_WATCHERR)
>>>>     WHILE nTries < 10
>>>>
>>>>            DBAPPEND(TRUE)
>>>>            IF !NetErr()
>>>>                LeaveCriticalSection(@CS_WATCHERR)
>>>>               RETURN TRUE
>>>>            ENDIF
>>>>            ++nTries
>>>>            Sleep(50)
>>>>     ENDDO
>>>>     LeaveCriticalSection(@CS_WATCHERR)
>>>>     RETURN FALSE
>>>> FUNCTION EditDbf()
>>>>     LOCAL nTries := 0 AS INT
>>>>
>>>>     WHILE nTries < 10
>>>>         ++nTries
>>>>         //IF DBRLOCK(RECNO())
>>>>         IF DBRLOCK()
>>>>             RETURN TRUE
>>>>         ENDIF
>>>>         IF nTries < 5
>>>>             Sleep(100)
>>>>             LOOP
>>>>         ENDIF
>>>>         IF MessageBox(0, PSZ("Unable to lock record"), ;
>>>>             PSZ("Record Lock Failure"), MB_RETRYCANCEL +
>>>> MB_ICONEXCLAMATION) != IDRETRY
>>>>             RETURN FALSE
>>>>         ENDIF
>>>>     ENDDO
>>>>     RETURN FALSE
>>>> FUNCTION OpenDbfQuiet(cFilename, cAliasname, lExclusive)
>>>>     LOCAL nTries := 0 AS INT
>>>>
>>>>     EnterCriticalSection(@CS_WATCHERR)
>>>>     IF IsNil(lExclusive)
>>>>         lExclusive := FALSE
>>>>     ENDIF
>>>>     IF IsNil(cAliasname)
>>>>         cAliasname := cFilename
>>>>     ENDIF
>>>>     IF SELECT(cAliasname) != 0    // Alias already in use
>>>>         cAliasname := Symbol2String(ConstructUniqueAlias(cFilename))
>>>>     ENDIF
>>>>
>>>>     WHILE nTries < 10
>>>>         ++nTries
>>>>         DBUSEAREA(TRUE, "DBFCDX", cFilename, cAliasname, !lExclusive,
>>>> FALSE)
>>>>         IF !NetErr()
>>>>             LeaveCriticalSection(@CS_WATCHERR)
>>>>             RETURN TRUE
>>>>         ENDIF
>>>>         Sleep(50)
>>>>     END
>>>>     LeaveCriticalSection(@CS_WATCHERR)
>>>>     RETURN FALSE
>>>>
>>>> Ginny
>>>>
>>>> "Martin"  wrote in message news:QGkwt.122934$G56.87814@fx32.fr7...
>>>>
>>>> Very interesting, you are using direct DBF rather than servers, I will
>>>> try that thankyou
>>>>
>>>> On 19/06/2013 15:02, Ginny Caughey wrote:
>>>>> Martin,
>>>>>
>>>>> I'm really not seeing anything obviously wrong here. Have you tried it
>>>>> without the Dynlock/Dynunlock? Here's my threaded code that ran
>>>>> without
>>>>> issues for several years. Maybe you'll spot something useful:
>>>>>
>>>>> FUNCTION RunPollingLoop( pInfo AS WatchInfo ) AS DWORD PASCAL    //
>>>>> Threaded function
>>>>>     LOCAL uMsg IS _winMsg    // used by thread message loop
>>>>>     LOCAL aParity AS ARRAY
>>>>>     LOCAL i AS INT
>>>>>     LOCAL cScale, cParity AS STRING
>>>>>     LOCAL nWeight, nTopWeight, nMinimumWt, nDelay AS INT
>>>>>     LOCAL dwStop AS DWORD
>>>>>     LOCAL dDate AS DATE
>>>>>     LOCAL cTime AS STRING
>>>>>     LOCAL oReader AS ScaleWatcher    // object that actually reads the
>>>>> scale and performs NTEP weight validation
>>>>>     LOCAL control, watchman, wconfig AS DWORD    // workareas for dbf
>>>>> files
>>>>>     LOCAL lError AS LOGIC
>>>>>
>>>>>     // Update status bar with scale started text
>>>>>     PostMessage(pInfo.hWnd, MSG_StartStop, pInfo.ScaleNumber,
>>>>> ScaleStarted)
>>>>>
>>>>>     // read paramters for this scale from wconfig and control files
>>>>>     aParity := { {"E", EvenParity}, ;
>>>>>                 {"M", MarkParity}, ;
>>>>>                 {"N", NoParity}, ;
>>>>>                 {"O", OddParity}, ;
>>>>>                 {"S", SpaceParity}     }
>>>>>
>>>>>     BEGIN SEQUENCE
>>>>>         IF !OpenDbfQuiet("control")
>>>>>             BREAK
>>>>>         ENDIF
>>>>>         control := DBGETSELECT()
>>>>>         IF !OpenDbfQuiet("wconfig")
>>>>>             BREAK
>>>>>         ENDIF
>>>>>         wconfig := DBGETSELECT()
>>>>>         IF !OpenDbfQuiet("watchman")
>>>>>             BREAK
>>>>>         ENDIF
>>>>>         watchman := DBGETSELECT()
>>>>>     RECOVER
>>>>>         lError := TRUE
>>>>>         HandleError("Unable to open a file needed to run Watchman Mode
>>>>> processing.")
>>>>>         IF control > 0
>>>>>             DBSELECTAREA(control)
>>>>>             DBCLOSEAREA()
>>>>>         ENDIF
>>>>>         IF wconfig > 0
>>>>>             DBSELECTAREA(wconfig)
>>>>>             DBCLOSEAREA()
>>>>>         ENDIF
>>>>>         IF watchman > 0
>>>>>             DBSELECTAREA(watchman)
>>>>>             DBCLOSEAREA()
>>>>>         ENDIF
>>>>>     END SEQUENCE
>>>>>
>>>>>     IF lError
>>>>>         RETURN 0
>>>>>     ENDIF
>>>>>
>>>>>     PostMessage(pInfo.hWnd, MSG_GettingData, pInfo.ScaleNumber, 0)
>>>>>     oReader := ScaleWatcher{pInfo.hWnd}
>>>>>     oReader:CommPort := "Com"+ NTrim(pInfo.PortNumber)
>>>>>     Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Getting info for
>>>>> scale")
>>>>>
>>>>>     // Get info for this scale port from control file
>>>>>     cScale := Str(pInfo.ScaleNumber,1,0)
>>>>>     nMinimumWt := (wconfig)->minimumwt
>>>>>     nDelay := (wconfig)->interval
>>>>>     (wconfig)->(DBCLOSEAREA())
>>>>>
>>>>>     oReader:Baud := (control)->(FIELDGET(FieldPos("baud"+cScale)))
>>>>>     oReader:Databits :=
>>>>> (control)->(FIELDGET(FieldPos("databits"+cScale)))
>>>>>     oReader:Stopbits :=
>>>>> (control)->(FIELDGET(FieldPos("stopbits"+cScale)))
>>>>>     IF oReader:Stopbits = 1
>>>>>         oReader:Stopbits := OneStopBit    // convert to Windows
>>>>> value (2
>>>>> = TwoStopBits already)
>>>>>     ENDIF
>>>>>     cParity := (control)->(FIELDGET(FieldPos("parity"+cScale)))
>>>>>     i := AScan(aParity, {|aVal| aVal[1] = cParity})
>>>>>     IF i > 0
>>>>>         oReader:Parity := aParity[i,2]
>>>>>     ELSE
>>>>>         oReader:Parity := NoParity
>>>>>     ENDIF
>>>>>     oReader:Buffsize :=
>>>>> (control)->(FIELDGET(FieldPos("buffsize"+cScale)))
>>>>>     oReader:WtBegin :=
>>>>> (control)->(FIELDGET(FieldPos("wtbegin"+cScale)))
>>>>>     oReader:WtLength :=
>>>>> (control)->(FIELDGET(FieldPos("wtlength"+cScale)))
>>>>>     oReader:CheckChar :=
>>>>> (control)->(FIELDGET(FieldPos("poll1chr"+cScale)))
>>>>>     oReader:CheckPosition :=
>>>>> (control)->(FIELDGET(FieldPos("poll2chr"+cScale)))
>>>>>     oReader:MaxRetries :=
>>>>> (control)->(FIELDGET(FieldPos("poll3chr"+cScale)))
>>>>>     oReader:MotionChar :=
>>>>> (control)->(FIELDGET(FieldPos("poll4chr"+cScale)))
>>>>>     oReader:MotionByte :=
>>>>> (control)->(FIELDGET(FieldPos("ack"+cScale)))
>>>>>     oReader:GrossLoc :=
>>>>> (control)->(FIELDGET(FieldPos("grossloc"+cScale)))
>>>>>     oReader:UnitLoc :=
>>>>> (control)->(FIELDGET(FieldPos("unitloc"+cScale)))
>>>>>     oReader:ScaleUnit := (control)->(FIELDGET(FieldPos("scaleunit")))
>>>>>     (control)->(DBCLOSEAREA())
>>>>>
>>>>>     // Run polling loop until WM_QUIT received from primary thread
>>>>>     // Polling is a two step process here:
>>>>>     //    1. Sample every nDelay seconds for a weigh large enough to
>>>>> indicate a vehicle
>>>>>     //    2. Once a vehicle is on the scale, sample at 1/10 second
>>>>> intervals to catch maximum weight
>>>>>     WHILE TRUE
>>>>>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - In polling
>>>>> loop")
>>>>>         //PostMessage(pInfo.hWnd, MSG_Polling, pInfo.ScaleNumber, 0)
>>>>>         IF PeekMessage(@uMsg, 0, 0, 0, PM_REMOVE)    // PeekMessage
>>>>> returns true if any messages in queue
>>>>>             IF uMsg.message == WM_QUIT
>>>>>                 EXIT
>>>>>             ENDIF
>>>>>         ENDIF
>>>>>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Getting first
>>>>> weight")
>>>>>         nWeight := oReader:ReadScale()
>>>>>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - nWeight is
>>>>> "+NTrim(nWeight))
>>>>>         IF oReader:CancelRequested
>>>>>             EXIT
>>>>>         ENDIF
>>>>>         IF nWeight = -1    // Error occurred
>>>>>             PostMessage(pInfo.hWnd, MSG_ScaleError,
>>>>> pInfo.ScaleNumber, 0)
>>>>>         ELSEIF nWeight < nMinimumWt
>>>>>             dwStop := GetTickCountLow()+DWORD(nDelay * 1000)
>>>>>             //PostMessage(pInfo.hWnd, MSG_Polling,
>>>>> pInfo.ScaleNumber, 0)
>>>>>             WHILE GetTickCountLow() <= dwStop
>>>>>                 IF PeekMessage(@uMsg, 0, 0, 0, PM_REMOVE)
>>>>>                     IF uMsg.message == WM_QUIT
>>>>>                         EXIT
>>>>>                     ENDIF
>>>>>                 ENDIF
>>>>>             END
>>>>>         ELSE
>>>>>             // We have a vehicle on scale
>>>>>             // Sample every 1/10 second until its maximum weight is
>>>>> captured
>>>>>             PostMessage(pInfo.hWnd, MSG_Sampling,
>>>>> pInfo.ScaleNumber, 0)
>>>>>             nTopWeight := nWeight
>>>>>             dDate := Today()
>>>>>             cTime := Time24()
>>>>>             WHILE TRUE
>>>>>                 IF PeekMessage(@uMsg, 0, 0, 0, PM_NOREMOVE)
>>>>>                     IF uMsg.message == WM_QUIT
>>>>>                         EXIT
>>>>>                     ENDIF
>>>>>                 ENDIF
>>>>>                 Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Testing
>>>>> for maximum weight")
>>>>>                 nWeight := oReader:ReadScale()
>>>>>                 IF oReader:CancelRequested
>>>>>                     EXIT
>>>>>                 ENDIF
>>>>>                 IF nWeight < nMinimumWt .AND. !oReader:MotionDetected
>>>>>                     EXIT
>>>>>                 ENDIF
>>>>>                 IF nWeight > nTopWeight
>>>>>                     nTopWeight := nWeight
>>>>>                     dDate := Today()
>>>>>                     cTime := Time24()
>>>>>                 ENDIF
>>>>>                 Sleep(100)    // give time slice to other threads for
>>>>> 1/10 second
>>>>>             END
>>>>>             IF uMsg.message != WM_QUIT .AND. !oReader:CancelRequested
>>>>>                 // Write out weight to file using file sharing
>>>>>                 IF (watchman)->(AddDbfQuiet())
>>>>>                     (watchman)->today := dDate
>>>>>                     (watchman)->time24 := cTime
>>>>>                     (watchman)->weight := nTopWeight
>>>>>                     (watchman)->scaleno := Str(pInfo.ScaleNumber,1,0)
>>>>>                     (watchman)->(DBCOMMIT())
>>>>>                     (watchman)->(DBUNLOCK())
>>>>>                 ELSE
>>>>>                     HandleError("Unable to add a record to the
>>>>> watchman
>>>>> file.")
>>>>>                 ENDIF
>>>>>             ELSE
>>>>>                 EXIT
>>>>>             ENDIF
>>>>>         ENDIF
>>>>>         IF uMsg.message == WM_QUIT .OR. oReader:CancelRequested
>>>>>             EXIT
>>>>>         ENDIF
>>>>>     END
>>>>>     Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Shutting down
>>>>> thread")
>>>>>     (watchman)->(DBCLOSEAREA())
>>>>>     RETURN 0
>>>>> FUNCTION Output( s AS STRING ) AS VOID PASCAL    // thread-safe way to
>>>>> write to log file
>>>>>     IF hDebug != NULL_PTR
>>>>>         EnterCriticalSection(@CS_DEBUG)
>>>>>         FWriteLine(hDebug, s)
>>>>>         LeaveCriticalSection(@CS_DEBUG)
>>>>>     ENDIF
>>>>>     RETURN
>>>>> FUNCTION HandleError(cError AS STRING) AS VOID PASCAL
>>>>>     LOCAL hFile AS PTR
>>>>>
>>>>>     // Thread-safe write to log file
>>>>>     EnterCriticalSection(@CS_WATCHERR)
>>>>>     IF File(GetDefault()+"watcherr.log")
>>>>>         hFile := FOpen(GetDefault()+"watcherr.log", FO_READWRITE)
>>>>>         FSeek(hFile, 0, FS_END)
>>>>>     ELSE
>>>>>         hFile := FCreate(GetDefault()+"watcherr.log")
>>>>>     ENDIF
>>>>>     IF hFile != F_ERROR
>>>>>         FWrite(hFile, DToC(Today())+" "+Time24()+"
>>>>> "+cError+_CHR(13)+_CHR(10))
>>>>>         FClose(hFile)
>>>>>     ENDIF
>>>>>     LeaveCriticalSection(@CS_WATCHERR)
>>>>> Ginny
>>>>>
>>>>> "Martin"  wrote in message news:vMgwt.107261$4C2.78184@fx23.fr7...
>>>>>
>>>>> Here we go Ginny
>>>>>
>>>>>
>>>>> Thanks
>>>>>
>>>>> Martin
>>>>>
>>>
>>
> 

[toc] | [prev] | [next] | [standalone]


#5400

FromMartin <spam@spam.spam>
Date2013-06-21 17:15 +0100
Message-ID<A__wt.158885$OL1.47275@fx13.fr7>
In reply to#5399
Now working, had to move all the app names into a shared place so they 
were the same, could not get the class one to work

On 21/06/2013 17:12, Ginny Caughey wrote:
> Here's the gist of it:
> http://social.msdn.microsoft.com/Forums/windows/en-US/ccee7ae6-75ca-4916-89cf-a099d12074a7/send-message-to-other-process
>
>
> This sample indicates you can pass null as the first parameter to
> FindWindow() and the windows title as the second:
> http://social.msdn.microsoft.com/Forums/en-US/18e41215-fc0f-4322-b942-4e1e90bafa48/c-findwindow
>
>
> These samples use SendMessage, which is a blocking call, but you may
> prefer PostMessage, which isn't.
>
> Ginny
>
> "Martin"  wrote in message news:IOZwt.96404$Ii.66384@fx19.fr7...
>
> FindWindow - now how do I make it work by class?
>
> On 21/06/2013 15:39, Martin wrote:
>> Postmessage between applications - need to read up on that, just what I
>> need
>>
>> On 21/06/2013 11:54, Ginny Caughey wrote:
>>> I really think you'll be happier with that approach. Multithreading can
>>> work in VO with DBF access, but it's tricky. The communication between
>>> windows using PostMessage used inside a multithreaded app can also be
>>> used across apps, so there's no real advantage to having everything in
>>> one app.
>>>
>>> Ginny
>>>
>>> "Martin (BT)"  wrote in message
>>> news:z5idnQZjZaab9V7MnZ2dnUVZ8uSdnZ2d@bt.com...
>>>
>>> I think I will have to go down the seperate .exe route, not good, but I
>>> have
>>> linked in a few thousand lines of library code.
>>>
>>>
>>> "Ginny Caughey" <gcaughey@online.hotmail.com> wrote in message
>>> news:51c34422$0$57923$c3e8da3$eb767761@news.astraweb.com...
>>>> If your UI thread is accessing DBF files without using the same DBF
>>>> functions as the worker thread, that could be the issue.
>>>>
>>>> Ginny
>>>>
>>>> "Martin"  wrote in message news:ARFwt.114422$P_4.83439@fx31.fr7...
>>>>
>>>> Thanks Ginny
>>>>
>>>> Just been testing since we have got the server running (blew up after
>>>> power cut despite UPS), with thread running the scanning code (main
>>>> .exe) crashes accessing the barcode system. thread carries on running
>>>> until I quit.
>>>>
>>>> Not using servers in thread, but Clipper style, any access controlled
>>>> with critical sections
>>>>
>>>> Note the same type of error in two files, both are open in the thread
>>>> with their own opens.
>>>>
>>>> Arg:             uField
>>>> ArgNum:          0
>>>> Args:          1 BC_ORDER : SYMBOL
>>>> ArgType:         NIL
>>>> ArgTypeReq:      NIL
>>>> CallFuncSym:     FIELDGET
>>>> CanDefault:      .F.
>>>> CanRetry:        .F.
>>>> CanSubstitute:   .F.
>>>> Description:     Wrong field specification
>>>>
>>>>
>>>>
>>>> Error Detail
>>>> Arg:             uField
>>>> ArgNum:          0
>>>> Args:          1 PL_DATE : SYMBOL
>>>> ArgType:         NIL
>>>> ArgTypeReq:      NIL
>>>> CallFuncSym:     FIELDGET
>>>> CanDefault:      .F.
>>>> CanRetry:        .F.
>>>> CanSubstitute:   .F.
>>>> Description:     Wrong field specification
>>>> FileHandle:      0
>>>> FileName:
>>>> FuncPtr:         0x00000000
>>>> FuncSym:         FIELDGET
>>>> GenCode:         1 : Argument error
>>>> MaxSize:         0
>>>> MethodSelf:      BarList
>>>> Operation:
>>>> OsCode:          0 : Successful completion
>>>> Severity:        ERROR
>>>> SubCode:         0
>>>> SubCodeText:
>>>> SubstituteType:  NIL
>>>> SubSystem:       Database
>>>> Tries:           0
>>>>
>>>>
>>>>
>>>>
>>>> On 20/06/2013 12:22, Ginny Caughey wrote:
>>>>> Here are the wrapper functions I'm using:
>>>>>
>>>>> FUNCTION AddDbf()
>>>>>     LOCAL dwStop AS DWORD
>>>>>
>>>>>     WHILE TRUE
>>>>>         dwStop := GetTickCountLow()+5000
>>>>>         WHILE GetTickCountLow() < dwStop
>>>>>                DBAPPEND()
>>>>>                IF ! NetErr()
>>>>>                   RETURN TRUE
>>>>>                ENDIF
>>>>>                Sleep(100)
>>>>>         ENDDO
>>>>>         IF MessageBox(0, PSZ("Unable to add a record to file"), ;
>>>>>             PSZ("Append Failure"), MB_RETRYCANCEL +
>>>>> MB_ICONEXCLAMATION)
>>>>> != IDRETRY
>>>>>             EXIT
>>>>>         ENDIF
>>>>>     END
>>>>>     RETURN FALSE
>>>>> STATIC FUNCTION ConstructUniqueAlias( cFileName AS STRING ) AS SYMBOL
>>>>> PASCAL
>>>>>     // Borrowed from 1.0c SDK in dbfsrvr.prg
>>>>>     LOCAL cTryNewAlias AS STRING
>>>>>     LOCAL w AS DWORD
>>>>>
>>>>>     IF IsNil(cFileName)
>>>>>         cFileName := "NOFILENAME"
>>>>>     ELSEIF ( w := At( ".", cFileName ) )>0
>>>>>         cFileName := SubStr( cFileName, 1, w-1 )
>>>>>     ENDIF
>>>>>     w := 1
>>>>>     cTryNewAlias := Upper(cFileName)
>>>>>
>>>>>     DO WHILE VODBSymSelect( String2Symbol( cTryNewAlias ) )>0
>>>>>         cTryNewAlias := Upper(cFileName)+"_"+AllTrim( Str( w++ ) )
>>>>>     ENDDO
>>>>>
>>>>>     RETURN String2Symbol(cTryNewAlias)
>>>>> FUNCTION XOpenDBF(cFilename)
>>>>>     RETURN OpenDbf(cFilename, , TRUE)
>>>>> FUNCTION OpenDbf(cFilename, cAliasname, lExclusive)
>>>>>     LOCAL dwStop AS DWORD
>>>>>     LOCAL lRet AS LOGIC
>>>>>
>>>>>     IF IsNil(lExclusive)
>>>>>         lExclusive := FALSE
>>>>>     ENDIF
>>>>>     IF IsNil(cAliasname)
>>>>>         cAliasname := cFilename
>>>>>     ENDIF
>>>>>     IF SELECT(cAliasname) != 0    // Alias already in use
>>>>>         cAliasname := Symbol2String(ConstructUniqueAlias(cFilename))
>>>>>     ENDIF
>>>>>     BEGIN SEQUENCE
>>>>>         WHILE TRUE
>>>>>             dwStop := GetTickCountLow()+5000 // allow .5 sec. retry
>>>>>             WHILE GetTickCountLow() <= dwStop
>>>>>                 Sleep(100)
>>>>>                 DBUSEAREA(TRUE, , cFilename, cAliasname, !lExclusive,
>>>>> FALSE)
>>>>>                 // use (cFilename) ALIAS (cAliasname) shared new
>>>>>                 IF ! NetErr()
>>>>>                     lRet := TRUE
>>>>>                     BREAK
>>>>>                 ENDIF
>>>>>             END
>>>>>             IF MessageBox(0, PSZ("Unable to open file "+cFilename), ;
>>>>>                 PSZ("File Open Error"), MB_RETRYCANCEL +
>>>>> MB_ICONEXCLAMATION) != IDRETRY
>>>>>                 EXIT
>>>>>             ENDIF
>>>>>         ENDDO
>>>>>     END SEQUENCE
>>>>>     IF lRet
>>>>>         cFilename := Upper(cFilename)
>>>>>         DO CASE
>>>>>             CASE cFilename = "RATECODE"
>>>>>                 DBFIELDINFO(DBS_ALIAS, FieldPos("code"), "_code")
>>>>>             CASE cFilename = "TICKET"
>>>>>                 DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
>>>>>             CASE cFilename = "INVOICE"
>>>>>                 DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
>>>>>             CASE cFilename = "HISTORY"
>>>>>                 DBFIELDINFO(DBS_ALIAS, FieldPos("date"), "_date")
>>>>>         ENDCASE
>>>>>     ENDIF
>>>>>     RETURN lRet
>>>>> FUNCTION AddDbfQuiet()
>>>>>     LOCAL nTries := 0 AS INT
>>>>>
>>>>>     EnterCriticalSection(@CS_WATCHERR)
>>>>>     WHILE nTries < 10
>>>>>
>>>>>            DBAPPEND(TRUE)
>>>>>            IF !NetErr()
>>>>>                LeaveCriticalSection(@CS_WATCHERR)
>>>>>               RETURN TRUE
>>>>>            ENDIF
>>>>>            ++nTries
>>>>>            Sleep(50)
>>>>>     ENDDO
>>>>>     LeaveCriticalSection(@CS_WATCHERR)
>>>>>     RETURN FALSE
>>>>> FUNCTION EditDbf()
>>>>>     LOCAL nTries := 0 AS INT
>>>>>
>>>>>     WHILE nTries < 10
>>>>>         ++nTries
>>>>>         //IF DBRLOCK(RECNO())
>>>>>         IF DBRLOCK()
>>>>>             RETURN TRUE
>>>>>         ENDIF
>>>>>         IF nTries < 5
>>>>>             Sleep(100)
>>>>>             LOOP
>>>>>         ENDIF
>>>>>         IF MessageBox(0, PSZ("Unable to lock record"), ;
>>>>>             PSZ("Record Lock Failure"), MB_RETRYCANCEL +
>>>>> MB_ICONEXCLAMATION) != IDRETRY
>>>>>             RETURN FALSE
>>>>>         ENDIF
>>>>>     ENDDO
>>>>>     RETURN FALSE
>>>>> FUNCTION OpenDbfQuiet(cFilename, cAliasname, lExclusive)
>>>>>     LOCAL nTries := 0 AS INT
>>>>>
>>>>>     EnterCriticalSection(@CS_WATCHERR)
>>>>>     IF IsNil(lExclusive)
>>>>>         lExclusive := FALSE
>>>>>     ENDIF
>>>>>     IF IsNil(cAliasname)
>>>>>         cAliasname := cFilename
>>>>>     ENDIF
>>>>>     IF SELECT(cAliasname) != 0    // Alias already in use
>>>>>         cAliasname := Symbol2String(ConstructUniqueAlias(cFilename))
>>>>>     ENDIF
>>>>>
>>>>>     WHILE nTries < 10
>>>>>         ++nTries
>>>>>         DBUSEAREA(TRUE, "DBFCDX", cFilename, cAliasname, !lExclusive,
>>>>> FALSE)
>>>>>         IF !NetErr()
>>>>>             LeaveCriticalSection(@CS_WATCHERR)
>>>>>             RETURN TRUE
>>>>>         ENDIF
>>>>>         Sleep(50)
>>>>>     END
>>>>>     LeaveCriticalSection(@CS_WATCHERR)
>>>>>     RETURN FALSE
>>>>>
>>>>> Ginny
>>>>>
>>>>> "Martin"  wrote in message news:QGkwt.122934$G56.87814@fx32.fr7...
>>>>>
>>>>> Very interesting, you are using direct DBF rather than servers, I will
>>>>> try that thankyou
>>>>>
>>>>> On 19/06/2013 15:02, Ginny Caughey wrote:
>>>>>> Martin,
>>>>>>
>>>>>> I'm really not seeing anything obviously wrong here. Have you
>>>>>> tried it
>>>>>> without the Dynlock/Dynunlock? Here's my threaded code that ran
>>>>>> without
>>>>>> issues for several years. Maybe you'll spot something useful:
>>>>>>
>>>>>> FUNCTION RunPollingLoop( pInfo AS WatchInfo ) AS DWORD PASCAL    //
>>>>>> Threaded function
>>>>>>     LOCAL uMsg IS _winMsg    // used by thread message loop
>>>>>>     LOCAL aParity AS ARRAY
>>>>>>     LOCAL i AS INT
>>>>>>     LOCAL cScale, cParity AS STRING
>>>>>>     LOCAL nWeight, nTopWeight, nMinimumWt, nDelay AS INT
>>>>>>     LOCAL dwStop AS DWORD
>>>>>>     LOCAL dDate AS DATE
>>>>>>     LOCAL cTime AS STRING
>>>>>>     LOCAL oReader AS ScaleWatcher    // object that actually reads
>>>>>> the
>>>>>> scale and performs NTEP weight validation
>>>>>>     LOCAL control, watchman, wconfig AS DWORD    // workareas for dbf
>>>>>> files
>>>>>>     LOCAL lError AS LOGIC
>>>>>>
>>>>>>     // Update status bar with scale started text
>>>>>>     PostMessage(pInfo.hWnd, MSG_StartStop, pInfo.ScaleNumber,
>>>>>> ScaleStarted)
>>>>>>
>>>>>>     // read paramters for this scale from wconfig and control files
>>>>>>     aParity := { {"E", EvenParity}, ;
>>>>>>                 {"M", MarkParity}, ;
>>>>>>                 {"N", NoParity}, ;
>>>>>>                 {"O", OddParity}, ;
>>>>>>                 {"S", SpaceParity}     }
>>>>>>
>>>>>>     BEGIN SEQUENCE
>>>>>>         IF !OpenDbfQuiet("control")
>>>>>>             BREAK
>>>>>>         ENDIF
>>>>>>         control := DBGETSELECT()
>>>>>>         IF !OpenDbfQuiet("wconfig")
>>>>>>             BREAK
>>>>>>         ENDIF
>>>>>>         wconfig := DBGETSELECT()
>>>>>>         IF !OpenDbfQuiet("watchman")
>>>>>>             BREAK
>>>>>>         ENDIF
>>>>>>         watchman := DBGETSELECT()
>>>>>>     RECOVER
>>>>>>         lError := TRUE
>>>>>>         HandleError("Unable to open a file needed to run Watchman
>>>>>> Mode
>>>>>> processing.")
>>>>>>         IF control > 0
>>>>>>             DBSELECTAREA(control)
>>>>>>             DBCLOSEAREA()
>>>>>>         ENDIF
>>>>>>         IF wconfig > 0
>>>>>>             DBSELECTAREA(wconfig)
>>>>>>             DBCLOSEAREA()
>>>>>>         ENDIF
>>>>>>         IF watchman > 0
>>>>>>             DBSELECTAREA(watchman)
>>>>>>             DBCLOSEAREA()
>>>>>>         ENDIF
>>>>>>     END SEQUENCE
>>>>>>
>>>>>>     IF lError
>>>>>>         RETURN 0
>>>>>>     ENDIF
>>>>>>
>>>>>>     PostMessage(pInfo.hWnd, MSG_GettingData, pInfo.ScaleNumber, 0)
>>>>>>     oReader := ScaleWatcher{pInfo.hWnd}
>>>>>>     oReader:CommPort := "Com"+ NTrim(pInfo.PortNumber)
>>>>>>     Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Getting info for
>>>>>> scale")
>>>>>>
>>>>>>     // Get info for this scale port from control file
>>>>>>     cScale := Str(pInfo.ScaleNumber,1,0)
>>>>>>     nMinimumWt := (wconfig)->minimumwt
>>>>>>     nDelay := (wconfig)->interval
>>>>>>     (wconfig)->(DBCLOSEAREA())
>>>>>>
>>>>>>     oReader:Baud := (control)->(FIELDGET(FieldPos("baud"+cScale)))
>>>>>>     oReader:Databits :=
>>>>>> (control)->(FIELDGET(FieldPos("databits"+cScale)))
>>>>>>     oReader:Stopbits :=
>>>>>> (control)->(FIELDGET(FieldPos("stopbits"+cScale)))
>>>>>>     IF oReader:Stopbits = 1
>>>>>>         oReader:Stopbits := OneStopBit    // convert to Windows
>>>>>> value (2
>>>>>> = TwoStopBits already)
>>>>>>     ENDIF
>>>>>>     cParity := (control)->(FIELDGET(FieldPos("parity"+cScale)))
>>>>>>     i := AScan(aParity, {|aVal| aVal[1] = cParity})
>>>>>>     IF i > 0
>>>>>>         oReader:Parity := aParity[i,2]
>>>>>>     ELSE
>>>>>>         oReader:Parity := NoParity
>>>>>>     ENDIF
>>>>>>     oReader:Buffsize :=
>>>>>> (control)->(FIELDGET(FieldPos("buffsize"+cScale)))
>>>>>>     oReader:WtBegin :=
>>>>>> (control)->(FIELDGET(FieldPos("wtbegin"+cScale)))
>>>>>>     oReader:WtLength :=
>>>>>> (control)->(FIELDGET(FieldPos("wtlength"+cScale)))
>>>>>>     oReader:CheckChar :=
>>>>>> (control)->(FIELDGET(FieldPos("poll1chr"+cScale)))
>>>>>>     oReader:CheckPosition :=
>>>>>> (control)->(FIELDGET(FieldPos("poll2chr"+cScale)))
>>>>>>     oReader:MaxRetries :=
>>>>>> (control)->(FIELDGET(FieldPos("poll3chr"+cScale)))
>>>>>>     oReader:MotionChar :=
>>>>>> (control)->(FIELDGET(FieldPos("poll4chr"+cScale)))
>>>>>>     oReader:MotionByte :=
>>>>>> (control)->(FIELDGET(FieldPos("ack"+cScale)))
>>>>>>     oReader:GrossLoc :=
>>>>>> (control)->(FIELDGET(FieldPos("grossloc"+cScale)))
>>>>>>     oReader:UnitLoc :=
>>>>>> (control)->(FIELDGET(FieldPos("unitloc"+cScale)))
>>>>>>     oReader:ScaleUnit := (control)->(FIELDGET(FieldPos("scaleunit")))
>>>>>>     (control)->(DBCLOSEAREA())
>>>>>>
>>>>>>     // Run polling loop until WM_QUIT received from primary thread
>>>>>>     // Polling is a two step process here:
>>>>>>     //    1. Sample every nDelay seconds for a weigh large enough to
>>>>>> indicate a vehicle
>>>>>>     //    2. Once a vehicle is on the scale, sample at 1/10 second
>>>>>> intervals to catch maximum weight
>>>>>>     WHILE TRUE
>>>>>>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - In polling
>>>>>> loop")
>>>>>>         //PostMessage(pInfo.hWnd, MSG_Polling, pInfo.ScaleNumber, 0)
>>>>>>         IF PeekMessage(@uMsg, 0, 0, 0, PM_REMOVE)    // PeekMessage
>>>>>> returns true if any messages in queue
>>>>>>             IF uMsg.message == WM_QUIT
>>>>>>                 EXIT
>>>>>>             ENDIF
>>>>>>         ENDIF
>>>>>>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Getting first
>>>>>> weight")
>>>>>>         nWeight := oReader:ReadScale()
>>>>>>         Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - nWeight is
>>>>>> "+NTrim(nWeight))
>>>>>>         IF oReader:CancelRequested
>>>>>>             EXIT
>>>>>>         ENDIF
>>>>>>         IF nWeight = -1    // Error occurred
>>>>>>             PostMessage(pInfo.hWnd, MSG_ScaleError,
>>>>>> pInfo.ScaleNumber, 0)
>>>>>>         ELSEIF nWeight < nMinimumWt
>>>>>>             dwStop := GetTickCountLow()+DWORD(nDelay * 1000)
>>>>>>             //PostMessage(pInfo.hWnd, MSG_Polling,
>>>>>> pInfo.ScaleNumber, 0)
>>>>>>             WHILE GetTickCountLow() <= dwStop
>>>>>>                 IF PeekMessage(@uMsg, 0, 0, 0, PM_REMOVE)
>>>>>>                     IF uMsg.message == WM_QUIT
>>>>>>                         EXIT
>>>>>>                     ENDIF
>>>>>>                 ENDIF
>>>>>>             END
>>>>>>         ELSE
>>>>>>             // We have a vehicle on scale
>>>>>>             // Sample every 1/10 second until its maximum weight is
>>>>>> captured
>>>>>>             PostMessage(pInfo.hWnd, MSG_Sampling,
>>>>>> pInfo.ScaleNumber, 0)
>>>>>>             nTopWeight := nWeight
>>>>>>             dDate := Today()
>>>>>>             cTime := Time24()
>>>>>>             WHILE TRUE
>>>>>>                 IF PeekMessage(@uMsg, 0, 0, 0, PM_NOREMOVE)
>>>>>>                     IF uMsg.message == WM_QUIT
>>>>>>                         EXIT
>>>>>>                     ENDIF
>>>>>>                 ENDIF
>>>>>>                 Output("Worker "+NTrim(pInfo.ScaleNumber)+"  -
>>>>>> Testing
>>>>>> for maximum weight")
>>>>>>                 nWeight := oReader:ReadScale()
>>>>>>                 IF oReader:CancelRequested
>>>>>>                     EXIT
>>>>>>                 ENDIF
>>>>>>                 IF nWeight < nMinimumWt .AND. !oReader:MotionDetected
>>>>>>                     EXIT
>>>>>>                 ENDIF
>>>>>>                 IF nWeight > nTopWeight
>>>>>>                     nTopWeight := nWeight
>>>>>>                     dDate := Today()
>>>>>>                     cTime := Time24()
>>>>>>                 ENDIF
>>>>>>                 Sleep(100)    // give time slice to other threads for
>>>>>> 1/10 second
>>>>>>             END
>>>>>>             IF uMsg.message != WM_QUIT .AND. !oReader:CancelRequested
>>>>>>                 // Write out weight to file using file sharing
>>>>>>                 IF (watchman)->(AddDbfQuiet())
>>>>>>                     (watchman)->today := dDate
>>>>>>                     (watchman)->time24 := cTime
>>>>>>                     (watchman)->weight := nTopWeight
>>>>>>                     (watchman)->scaleno := Str(pInfo.ScaleNumber,1,0)
>>>>>>                     (watchman)->(DBCOMMIT())
>>>>>>                     (watchman)->(DBUNLOCK())
>>>>>>                 ELSE
>>>>>>                     HandleError("Unable to add a record to the
>>>>>> watchman
>>>>>> file.")
>>>>>>                 ENDIF
>>>>>>             ELSE
>>>>>>                 EXIT
>>>>>>             ENDIF
>>>>>>         ENDIF
>>>>>>         IF uMsg.message == WM_QUIT .OR. oReader:CancelRequested
>>>>>>             EXIT
>>>>>>         ENDIF
>>>>>>     END
>>>>>>     Output("Worker "+NTrim(pInfo.ScaleNumber)+"  - Shutting down
>>>>>> thread")
>>>>>>     (watchman)->(DBCLOSEAREA())
>>>>>>     RETURN 0
>>>>>> FUNCTION Output( s AS STRING ) AS VOID PASCAL    // thread-safe
>>>>>> way to
>>>>>> write to log file
>>>>>>     IF hDebug != NULL_PTR
>>>>>>         EnterCriticalSection(@CS_DEBUG)
>>>>>>         FWriteLine(hDebug, s)
>>>>>>         LeaveCriticalSection(@CS_DEBUG)
>>>>>>     ENDIF
>>>>>>     RETURN
>>>>>> FUNCTION HandleError(cError AS STRING) AS VOID PASCAL
>>>>>>     LOCAL hFile AS PTR
>>>>>>
>>>>>>     // Thread-safe write to log file
>>>>>>     EnterCriticalSection(@CS_WATCHERR)
>>>>>>     IF File(GetDefault()+"watcherr.log")
>>>>>>         hFile := FOpen(GetDefault()+"watcherr.log", FO_READWRITE)
>>>>>>         FSeek(hFile, 0, FS_END)
>>>>>>     ELSE
>>>>>>         hFile := FCreate(GetDefault()+"watcherr.log")
>>>>>>     ENDIF
>>>>>>     IF hFile != F_ERROR
>>>>>>         FWrite(hFile, DToC(Today())+" "+Time24()+"
>>>>>> "+cError+_CHR(13)+_CHR(10))
>>>>>>         FClose(hFile)
>>>>>>     ENDIF
>>>>>>     LeaveCriticalSection(@CS_WATCHERR)
>>>>>> Ginny
>>>>>>
>>>>>> "Martin"  wrote in message news:vMgwt.107261$4C2.78184@fx23.fr7...
>>>>>>
>>>>>> Here we go Ginny
>>>>>>
>>>>>>
>>>>>> Thanks
>>>>>>
>>>>>> Martin
>>>>>>
>>>>
>>>
>>
>

[toc] | [prev] | [next] | [standalone]


#5383

Fromdlzc <dlzc1@cox.net>
Date2013-06-19 08:04 -0700
Message-ID<da80a66e-52c7-414a-9e41-82eabcb2f7f4@googlegroups.com>
In reply to#5380
Dear Martin:

On Wednesday, June 19, 2013 4:40:16 AM UTC-7, Martin wrote:
...
> LOCAL TBarList    AS bcBarList, ;
>        TBarCode    AS bcBarCode, ;
>        TOrder    AS bcOrder, ;
>        TDelList    AS bcDelList, ; //, a as csocket
>        strCtrl    AS CheckThreadControl, ;
>        pszRack    AS PSZ, ;
>        pszBat    AS PSZ, ;
>        pszProc    AS PSZ, ;
>        cOrder    AS STRING, ;
>        cCust        AS STRING, ;
>        cBarCode    AS STRING, ;
>        cProc        AS STRING, ;
>        nRack        AS DWORD, ;
>        lOk        AS LOGIC, ;
>        nCount    AS DWORD

... OK, move all these you can to a DBF, even if it has just one record.  You have strings, and strings will invoke garbage collection.  Since you will never have to move around, the OS will keep these hot for you with little performance hit.

What thread controls bcBarList, bcBarCode, bcOrder, bcDelList?

David A. Smith

[toc] | [prev] | [next] | [standalone]


#5384

FromMartin <spam@spam.spam>
Date2013-06-19 17:04 +0100
Message-ID<XDkwt.142621$LL5.115978@fx18.fr7>
In reply to#5383
They are my gui less versions of the 4 DBFs I am monitoring

Only using strings as that is what fieldget supplies me.

On 19/06/2013 16:04, dlzc wrote:
> Dear Martin:
>
> On Wednesday, June 19, 2013 4:40:16 AM UTC-7, Martin wrote:
> ...
>> LOCAL TBarList    AS bcBarList, ;
>>         TBarCode    AS bcBarCode, ;
>>         TOrder    AS bcOrder, ;
>>         TDelList    AS bcDelList, ; //, a as csocket
>>         strCtrl    AS CheckThreadControl, ;
>>         pszRack    AS PSZ, ;
>>         pszBat    AS PSZ, ;
>>         pszProc    AS PSZ, ;
>>         cOrder    AS STRING, ;
>>         cCust        AS STRING, ;
>>         cBarCode    AS STRING, ;
>>         cProc        AS STRING, ;
>>         nRack        AS DWORD, ;
>>         lOk        AS LOGIC, ;
>>         nCount    AS DWORD
>
> ... OK, move all these you can to a DBF, even if it has just one record.  You have strings, and strings will invoke garbage collection.  Since you will never have to move around, the OS will keep these hot for you with little performance hit.
>
> What thread controls bcBarList, bcBarCode, bcOrder, bcDelList?
>
> David A. Smith
>

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.clipper.visual-objects


csiph-web