HTTPRequest() not threadsafe?

Just starting out? Need help? Post your questions and find answers here.
wayne-c
Enthusiast
Enthusiast
Posts: 335
Joined: Tue Jun 08, 2004 10:29 am
Location: Zurich, Switzerland

HTTPRequest() not threadsafe?

Post by wayne-c »

PB 5.72 LTS Beta 2 (x64) / macOS AND Windows

Maybe you have to run the code multiple times, but here (macOS and Windows) sooner or later the errors occur...

Code: Select all

InitNetwork()

Procedure TestThread(Nr)
	Protected Response$ = ""
	Protected HttpRequest = HTTPRequest(#PB_HTTP_Post, "https://www.purebasic.com/", "" + Str(Nr))
	If HTTPRequest
		Response$ = HTTPInfo(HTTPRequest, #PB_HTTP_Response)
		FinishHTTP(HTTPRequest)
		Debug Str(Nr) + " --> " + StringByteLength(Response$)
	EndIf
EndProcedure

NewList Threads()
For k = 1 To 25
	AddElement(Threads())
	Threads() = CreateThread(@TestThread(), k)
Next
ForEach Threads()
	WaitThread(Threads())
Next
Expected: For every Request/Thread the same amount of bytes received

But the result is:

Code: Select all

0 --> 25684
13 --> 25684
4 --> 25684
2 --> 25684
15 --> 25684
8 --> 25684
24 --> 25684
25 --> 25684
23 --> 25684
12 --> 25684
6 --> 25684
10 --> 25684
19 --> 25684
3 --> 566
17 --> 566
7 --> 566
22 --> 25684
9 --> 566
5 --> 566
18 --> 566
21 --> 566
1 --> 25684
20 --> 566
11 --> 566
14 --> 566
16 --> 566
As you walk on by, Will you call my name? Or will you walk away?
Marc56us
Addict
Addict
Posts: 1479
Joined: Sat Feb 08, 2014 3:26 pm

Re: HTTPRequest() not threadsafe?

Post by Marc56us »

Add a little delay between requests.
Without that, server have no time to make page and block as flood (reply: 403 Forbidden)

Code: Select all

InitNetwork()

Procedure TestThread(Nr)
   Protected Response$ = ""
   Protected HttpRequest = HTTPRequest(#PB_HTTP_Post, "https://www.purebasic.com/", "" + Str(Nr))
   If HTTPRequest
      Response$ = HTTPInfo(HTTPRequest, #PB_HTTP_Response)
      FinishHTTP(HTTPRequest)
      Debug Str(Nr) + " --> " + StringByteLength(Response$)
      Debug Left(Response$, 100) ; See what happend if no delay 
   EndIf
EndProcedure

NewList Threads()
For k = 1 To 25
   AddElement(Threads())
   Threads() = CreateThread(@TestThread(), k)
   Delay(200) ; Add a little delay 
Next
ForEach Threads()
   WaitThread(Threads())
Next
:wink:
Post Reply