will
will

Reputation: 45

Retrieve data from threads

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

Answers (1)

svick
svick

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:

  1. Use 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.
  2. Don't share data between threads. If you have several operations that you want to run in parallel, some require resource A and others require resource B, run those that require A on one thread and those that require B on another thread. This way, you can be sure that only one thread accesses A or B, so it's safe. Another variant of this is if each thread has a copy of the resource.
  3. Use special thread-safe data structures. For example in .Net 4, there is a whole namespace of thread-safe collections: System.Collections.Concurrent.
  4. Use immutable data structures. If the structure doesn't change, it's safe to access it from several threads at the same time. For example, because of this it's safe to share a string between several threads.
  5. Use special constructs that avoid locking, like 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

Related Questions