PDA

View Full Version : SDL_CreateThread parameter 2



kotai
08-08-2010, 01:34 AM
Hi.

I use one SDL_CreateThread in my games, but now I need several Threads and I want to use param 2 in SDL_CreateThread to specify the data that hade use in each thread.


When I use only one thread the code is:



uses SDL;

var
thread: PSDL_Thread;
returnValue: Integer;

function thread_func(): Integer;
begin
// do threading here
WriteLn('Start Thread');
SDL_Delay(5000);
WriteLn('End Thread');

result := 1; // thread leaves and return this value
end;

begin
returnValue := 0;
thread := SDL_CreateThread(@thread_func, NIL);

SDL_WaitThread(thread, returnValue);
WriteLn('Thread returns code ',returnValue);
SDL_Quit;
WriteLn('ByeBye ;)');
end.



but now with several thread I test this:


uses SDL;

var
thread: PSDL_Thread;
returnValue: Integer;

function thread_func(MyData:TList): Integer;
begin
// do threading here
while MyData.Count > 0 do
begin
WriteLn('....');
MyDate.Delete(0);
end;
SDL_Delay(5000);
WriteLn('End Thread');

result := 1; // thread leaves and return this value
end;

begin
returnValue := 0;
MyList : TList.Create;
MyList.Add(....);
thread := SDL_CreateThread(@thread_func, MyList);

SDL_WaitThread(thread, returnValue);
WriteLn('Thread returns code ',returnValue);
SDL_Quit;
WriteLn('ByeBye ;)');
end.


but parameter2 do not pass to function, MyDate (in function) is always to NIL

How are passed the parameter 2?


Thanks

jdarling
09-08-2010, 01:25 PM
If this is pure SDL then your method convention is wrong and should be:


function thread_func(data : Pointer): LongInt; cdecl; // this may change depending on Delphi/Laz and SDL ver
var
myList : TList;
begin
myList := TList(data);
if(not assigned(myList))then
exit; // triple check and all

while myList.Count > 0 do
begin
WriteLn('....');
MyDate.Delete(0);
end;
SDL_Delay(5000);
WriteLn('End Thread');
result := 1; // thread leaves and return this value
end;


Remember, SDL is developed in C not pascal. C uses a different structure when passing variables (heap vs stack vs register) than Delphi/Laz/FPC/Pascal and so you have to tell it the difference. This doesn't make a difference when your not actually using the params, but when you start using them it quits working :). I'm guessing your in Delphi, as in Lazarus/FPC the posted code should never have compiled (FPC is very strict) or you have told FPC to act like Delphi (bad coder, no cookie).

If your using the Jedi SDL package there are examples of using the SDL thread. You can also use native threads and simply wrap up the important parts where you actually call SDL in Critical Sections, Mutexs, or Semiphores. Its a bit dated but here is a good read: http://www.eonclash.com/Tutorials/Multithreading/MartinHarvey1.1/ToC.html

- Jeremy

kotai
09-08-2010, 02:51 PM
Thanks !!!!!

The problem solved with "cdecl;"

I did not know the existence of this syntax.

Kotai.