Reputation: 45
I am trying to run two separate threads, like A and B. A and B running on totally different data, and A only need small part of data from B. They both need to be running all time. How can I retrieve the data from thread B and not interrupt B's running.
I am new to the multiple threads, could you tell me in examples?
Upvotes: 0
Views: 751
Reputation: 244837
That's not how threads work, threads don't “own” data (most of the time). You can access data that was used or created on another thread just like any other data, but it can be very dangerous to do so.
The problem is that most data structures are not ready to be accessed from more than one thread at the same time (they are not thread-safe). There are several ways how to fix that:
lock
(or some other synchronization construct) to access the shared resource. Doing this makes sure that only one thread accesses the resource at a time, so it's safe. This is the most general approach (it works every time), it's probably the most common solution and the one that is easiest to get right (just lock
on the right lock object every time you access the resource). But it can hurt performance, because it can make threads wait on each other a lot.System.Collections.Concurrent
.string
between several threads.Interlocked
operations or volatile
operations. This is how most of the structures from #3 are implemented internally and it's a solution that can be much more performant than #1. But it's also very hard to do this right, which is why you should avoid it unless you really know what you're doing.You have several options and it can be all confusing. But the best option usually is to just use a lock
to access the shared resource, or use a thread-safe structure from a library and doing that is not hard. But if you find out that's not enough, you can go for the more advanced alternatives, but it will be hard to get right.
Upvotes: 2