Questions about 'Threads'

I’m trying to learn threads and what they actually do, so I got some questions regarding it.

1- So a thread basically lets us run code that doesn’t affect other code? Is my understanding correct or mistaken?

2- Does that mean that task.spawn creates a new ‘thread’ that doesn’t affect/interfere with the main thread?

1 Like

Hi, I’m not very good at explaining but I can give you a little idea:

  1. A thread allows code to run concurrently, meaning that you can do multiple things at once. Each thread has its own execution context and stack, but all the threads share the same memory space, allowing them to read and write to shared variables.

  2. Yes, you are right. Creating a new thread separates the execution stack from the main thread. Meaning you will be able to run multiple tasks concurrently.

Be careful of race conditions in case you’re trying to modify the same data from two different threads.

2 Likes

Yes, your understanding is right.

When you run a code inside a thread, it runs without yielding the main code, this means that you can run multiple threads allowing you to run multiple tasks at the same time without any yielding, it still shares the same memory space though, which means that they can interfere with each other if they access the same shared data.

1 Like