We are currently migrating Bugzilla to GitHub issues.
Any changes made to the bug tracker now will be lost, so please do not post new bugs or make changes to them.
When we're done, all bug URLs will redirect to their equivalent location on the new bug tracker.

Bug 5064

Summary: Remove semaphore from SDL_CreateThread
Product: SDL Reporter: Ryan C. Gordon <icculus>
Component: threadAssignee: Sam Lantinga <slouken>
Status: RESOLVED FIXED QA Contact: Sam Lantinga <slouken>
Severity: normal    
Priority: P2 Keywords: target-2.0.14
Version: HG 2.0   
Hardware: All   
OS: Other   
Attachments: Attempt at simplfying this

Description Ryan C. Gordon 2020-03-27 01:42:59 UTC
So it looks like from here:

- App calls SDL_CreateThread*
- SDL_CreateThread allocates some data, creates a semaphore, calls into SDL_SYS_CreateThread
- SDL_SYS_CreateThread spins a thread and calls SDL_RunThread on the new thread, and returns to SDL_CreateThread*
- SDL_CreateThread waits on the semaphore.
- SDL_RunThread sets up some stuff, posts to the semaphore, and calls the app's actual thread entry point.
- SDL_CreateThread sees the semaphore has posted, takes this as an indication that it's safe to free the data it allocated.

...is there any reason we can't do this:
- Don't create a semaphore at all.
- SDL_RunThread frees the data before calling the app's entry point.
- SDL_CreateThread frees the data if SDL_SYS_CreateThread fails, otherwise it leaves it alone.

This means SDL won't have to create a semaphore and won't have to wait for the new thread at all.

The other benefit: Emscripten with pthread support doesn't actually create the thread until the next iteration through the mainloop, so it _can't_ safely wait here by default, as the thread will never post to the semaphore because the thread won't be created at all until some time after SDL_CreateThread returns.

All this to say: is this a _safe_ change to make, or was the semaphore approach done for a specific reason?

--ryan.
Comment 1 Ryan C. Gordon 2020-03-27 01:48:11 UTC
...or just make "data" and "func" from thread_args part of SDL_Thread, and don't free anything extra at all...

--ryan.
Comment 2 Ryan C. Gordon 2020-03-27 02:40:30 UTC
Created attachment 4281 [details]
Attempt at simplfying this


Here's a patch to clean it up. Unless it was super important, this nukes a bunch of code, some memory management and a semaphore, and should fix Emscripten threads too.

--ryan.
Comment 3 Sam Lantinga 2020-03-27 22:13:58 UTC
Looks good!
https://hg.libsdl.org/SDL/rev/498a7f27758e