I am curious about the best way to share data between threads that aren't based on the same method.
For example, if I want to share the same string(by reference) between 2 threads:
Main()
{
string shareme;
Start New Thread based on A()
Start New Thread based on B()
shareme = "Updated in main";
}
A()
{
shareme = "Updated in A";
}
B()
{
shareme = "Updated in B";
}
Thanks
Loading
VulpesPosted Apr 10, 2013, 4:12 PM
For example, if we make your code into an executable program and run it multiple times:
using System;
using System.Threading;
class Program
{
string shareme;
static Program p = new Program();
static void Main()
{
Program p = new Program();
Thread t1 = new Thread(p.A);
Thread t2 = new Thread(p.B);
t1.Start();
t2.Start();
p.shareme = "Updated in main";
Console.WriteLine(p.shareme);
Console.ReadKey();
}
void A()
{
p.shareme = "Updated in A";
Console.WriteLine(p.shareme);
}
void B()
{
p.shareme = "Updated in B";
Console.WriteLine(p.shareme);
}
}
The order of the output is completely unpredictable. It might be :
Updated in main
Updated in A
Updated in B
bit it could be other permutations as well.
Suppose we wanted it to always be:
Updated in A
Updated in B
Updated in main
then we could achieve that by adding a lock in A() and then 'joining' both threads in the main thread so that the latter's Console.WriteLine always executes last:
using System;
using System.Threading;
class Program
{
static object padLock = new object();
string shareme;
static Program p = new Program();
static void Main()
{
Program p = new Program();
Thread t1 = new Thread(p.A);
Thread t2 = new Thread(p.B);
t1.Start();
t1.Join();
t2.Start();
t2.Join();
p.shareme = "Updated in main";
Console.WriteLine(p.shareme);
Console.ReadKey();
}
void A()
{
lock(padLock)
{
p.shareme = "Updated in A";
Console.WriteLine(p.shareme);
}
}
void B()
{
p.shareme = "Updated in B";
Console.WriteLine(p.shareme);
}
}
The lock ensures that the B thread doesn't have a chance to update shareme before thread A can print it to the console.
VulpesPosted Apr 10, 2013, 6:56 PM