C
C#2y ago
boom

✅ Mutexing List

I have a service that spawns a thread to execute functions, and the list being access inside the spawned thread is inside of another thread. how do i mutex a list between 2 threads?
15 Replies
boom
boom2y ago
basically, the spawned threads are going to remove themselves from the list, but i feel there will be a mutex issue removing the items from the list if they finish at odd times
333fred
333fred2y ago
You don't mutex a list, you use a synchronization primitive (such as a mutex) to synchronize the threads
boom
boom2y ago
so, basically create a bool that locks the access to removing/adding items from the list
333fred
333fred2y ago
And it's not hard. As an example:
class MyClass
{
private readonly List<string> list = new();
private readonly object listLock = new();
public void M()
{
lock (listLock) { /* Do things on the list */ }
}
}
class MyClass
{
private readonly List<string> list = new();
private readonly object listLock = new();
public void M()
{
lock (listLock) { /* Do things on the list */ }
}
}
Not a bool, a lock
boom
boom2y ago
oooo i see
333fred
333fred2y ago
A boolean field is not a sufficient synchronization primitive on its own
boom
boom2y ago
good information, appreciated. i will give this a go
333fred
333fred2y ago
lock statement - synchronize thread access to a shared resource
Use the C# lock statement to ensure that only a single thread exclusively reads or writes a shared resource, blocking all other threads until it completes.
333fred
333fred2y ago
There's a lot more to learn when it comes to synchronization, but this is the basic version
boom
boom2y ago
this is a little bit more than i thought it'd be xd
333fred
333fred2y ago
Synchronization always is
boom
boom2y ago
then again, the threads i was working with weren't real threads python 🤢 i'll study this to my needs, thanks
333fred
333fred2y ago
If you don't have any other questions, consider $close ing the thread
MODiX
MODiX2y ago
Use the /close command to mark a forum thread as answered
Accord
Accord2y ago
Closed!
Want results from more Discord servers?
Add your server
More Posts