Thread series 03: multi-thread data sharing; 03: multi-thread data sharing
Multi-threaded programming sometimes requires that the data of each thread be isolated from each other, but sometimes requires that data can be shared and synchronized between threads. This article describes how to share and not share data with multiple threads.
□Multithreading does not share data
For multithreading, how does CLR allocate memory stack space for them? Is it "a radish and a pitfall", and each thread has its own stack space; or "Good luck under a big tree", all threads share the same stack space?
Let two threads execute the same static method, use the same variables, and print the variables to verify the allocation of multi-thread stack space.
class Program
{
static void Main(string[] args)
{
new Thread(SayHi).Start();
SayHi();
}
static void SayHi()
{
for (int i = 0; i < 5; i++)
{
Console. WriteLine ("I Am a Thread #" + Thread. CurrentThread. ManagedThreadId + "this is my" + I + "hello ");
}
}
}
Although two threads run in parallel, they all say hello for four times. This indicates that the CLR allocates stack space for both threads, and variable I is mutually independent from each other in their respective stack spaces.
□Multi-thread data sharing
Threads need to cooperate with each other. How can multiple threads share data?
※Shared instance variable
Let two threads execute the same instance method to see if the common fields of the object instance can be shared.
using System;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
public int whatever;
static void Main(string[] args)
{
Program p = new Program();
new Thread(p.PrintVariable).Start();
p.PrintVariable();
}
void PrintVariable()
{
whatever++;
Console. WriteLine ("Thread #" + Thread. CurrentThread. ManagedThreadId + "after execution, the whatever variable is:" + whatever );
}
}
}
It can be seen that the two threads share the common fields of the Program instance.
In addition, the topic of sharing data between threads is: how to avoid data synchronization? The lock block can solve this problem. At the same time, only one thread is allowed to enter the method. This is also called "thread security ".
class Program
{
public int whatever;
// Static readonly value assigned to variables during compilation
static readonly object locker = new object();
static void Main(string[] args)
{
Program p = new Program();
new Thread(p.PrintVariable).Start();
p.PrintVariable();
}
void PrintVariable()
{
lock (locker)
{
whatever++;
Console. WriteLine ("Thread #" + Thread. CurrentThread. ManagedThreadId + "after execution, the whatever variable is:" + whatever );
}
}
}
When one thread is executed in the lock block and the other thread is waiting, the waiting thread does not consume CPU at that moment.
※Share static Fields
class Program
{
static int whatever;
// Static readonly value assigned to variables during compilation
static readonly object locker = new object();
static void Main(string[] args)
{
new Thread(PrintVariable).Start();
PrintVariable();
}
static void PrintVariable()
{
lock (locker)
{
whatever++;
Console. WriteLine ("Thread #" + Thread. CurrentThread. ManagedThreadId + "after execution, the whatever variable is:" + whatever );
}
}
}
Summary:
○ CLR allocates memory stack space to each thread. the variables in the stack do not affect each other.
○ Multiple threads can share static fields of common members and classes of object instances.
○ "Thread security" must be taken into account for data sharing between threads. The use of lock statement blocks ensures "thread security"
The thread series includes:
Thread series 01, front-end thread, back-end thread, thread synchronization thread series 02, multiple threads simultaneously process a time-consuming task to save time thread series 03, multi-thread shared data, multi-thread data sharing
A java multi-thread data sharing example,
Public class ThreadPoolManager {
Private static ThreadPoolManager instance = null;
Private List <Upload> taskQueue = Collections. synchronizedList (new queue List <Upload> (); // task queue
Private WorkThread [] workQueue; // working thread (the thread that actually executes the task)
Private static int worker_num = 6; // Number of worker threads (the default number of worker threads is 6)
Private static int worker_count = 0;
Private ThreadPoolManager (){
This (6 );
}
Private ThreadPoolManager (int num ){
Worker_num = num;
WorkQueue = new WorkThread [worker_num];
For (int I = 0; I <worker_num; I ++ ){
WorkQueue [I] = new WorkThread (I );
}
}
Public static synchronized ThreadPoolManager getInstance (){
If (instance = null)
Instance = new ThreadPoolManager ();
Return instance;
}
Public void addTask (Upload task ){
// Lock operations on the task queue
Synchronized (taskQueue ){
If (task! = Null ){
TaskQueue. add (task );
TaskQueue. policyall ();
System. out. println ("task id" + task. getInfo () + "submit! ");
}
}
}
Public void BatchAddTask (Upload [] tasks ){
// Lock the modification operation on the task queue
Synchronized (taskQueue ){
For (Upload e: tasks ){
If (e! = Null ){
TaskQueue. add (e );
TaskQueue. policyall ();
System. out. println ("t... the remaining full text>
C # multi-thread data sharing
It is not difficult to share data. You only need to pass in the data object you want to share before the thread starts (usually when constructing the thread object) when creating the thread object. Note:
1. The shared data must be thread-safe because it involves concurrent access from two threads.
2. Other Object references of shared data must also be thread-safe. If you need to access them.
Post Code:
Object jsonobject; // init object you need.
Var t1 = new System. Threading. Thread (arg =>
{// Arg is invalid object
});
Var t2 = new System. Threading. Thread (arg =>
{// Arg is invalid object
});
T1.Start (jsonobject );
T2.Start (jsonobject );