In the main code, adding one million elements needs a certain time.
When I now run the same code in a thread, it should need the same time or similar time.
And when I run the same code in multiple independent threads, they should all need again the same time.
But now see what happens (code edited!):
Code: Select all
CompilerIf Not #PB_Compiler_Thread
CompilerError "Enable Thread-Safe"
CompilerEndIf
Threaded NewList Integer.i()
Procedure Test(Void.i=0)
Protected I.i
For I = 1 To 1000000
AddElement(Integer())
Next
ClearList(Integer())
EndProcedure
Define Time.i, Threads.i
Define NewList Thread.i()
OpenConsole()
Time = ElapsedMilliseconds()
Test()
Time = ElapsedMilliseconds() - Time
PrintN("Single Main Thread: "+Str(Time)+" ms")
For Threads = 1 To 4
Time = ElapsedMilliseconds()
For I = 1 To Threads
AddElement(Thread()) : Thread() = CreateThread(@Test(), 0)
PrintN("CreateThread")
Next
ForEach Thread()
WaitThread(Thread())
Next
ClearList(Thread())
Time = ElapsedMilliseconds() - Time
PrintN(Str(Threads)+" Thread(s): "+Str(Time)+" ms")
Next
Input()
As soon as more than one thread is calling AddElement() the running time slows down. But why? There is no interaction between the Lists, because they are initialized with Threaded.Single Main Thread: 32 ms
CreateThread
1 Thread(s): 32 ms
CreateThread
CreateThread
2 Thread(s): 187 ms
CreateThread
CreateThread
CreateThread
3 Thread(s): 640 ms
CreateThread
CreateThread
CreateThread
CreateThread
4 Thread(s): 1014 ms
Can anybody confirm this behavior?
Can anybody explain this behavior?
A solution is the use of an own memory allocation module: slab allocator (see later in this thread)
I observed this issue during some parallelization of a code block, but instead of saving time, it takes more time