Mixing Thread types

When preemptive Threads were introduced, the understanding was that you could not protect code that was being simultaneously accessed in preemptive and cooperative threads because the classes that are meant to protect it (Semaphore and CriticalSection) had to be set to match the Thread.Type.

That was then.

It is still true that Semaphores cannot be used among mixed Thread types, but a CriticalSection can if its Type is set to Preemptive.

To be really clear, if you create a CriticalSection and set its Type to Preemptive, it can be called from either a preemptive or cooperative Thread without raising an error, and will serve to protect a code block when called from either, or both simultaneously.

The Xojo documentation was updated recently to reflect this, and the change should make it easier to convert Threads in stages, or just mix preemptive with cooperative Threads.

3 Likes

Is that for real, after all the page also says:

Because preemptive Threads can execute on any available core, they do not share memory with each other nor with your app as cooperative Threads do. This means the code in the Thread will have no access to the values of any other objects in your app.

Which isn’t true.

If type mixing is true, it sounds very useful.

Hi Kem.

Does that also include the main thread?

Yes, that’s true for both Semaphore and CS.

That is really good news as there was a discussion on the forum a while back where it was stated by William that this was not possible.

I didn’t see that, and you’re right, that’s incorrect.

Yes, that was the thinking at the time, but his opinion changed, and I tested the heck out of it. :slight_smile:

2 Likes

Yes, I have a bug report against it. It’s supposed to be fixed in the next version.

Cool.

To be even clearer-er…

A Semaphore set to Cooperative can be used in Main and any number of Cooperative Threads, but may not be used in a Preemptive Thread.

A Semaphore set to Preemptive can be used in Main and any number of Preemptive Threads, but may not be used in a Cooperative Thread.

A CriticalSection set to Cooperative can be used in Main and any number of Cooperative Threads, but may not be used in a Preemptive Thread.

None of that has changed since Preemptive Threads were introduced. What has changed is…

A CriticalSection set to Preemptive can be used in Main and any number of Threads regardless of their types.

2 Likes

Sounds like we need a new constant ThreadType.Universal to clear up the confusion.

This is a huge win, given that it makes threading much much more easier.

1 Like