Thread, the thread pool, concurrency, synchronous, asynchronous, lock

Look at a simulation of multiple threads simultaneously write 1000 log example:


class Program {

    static void Main(string[] args) {


        Thread t1 = new Thread(Working);

        t1.Name = "Thread1"; // instantiate three threads to write the log.

        Thread t2 = new Thread(Working);

        t2.Name = "Thread2";

        Thread t3 = new Thread(Working);

        t3.Name = "Thread3";


        // turn starts three threads.

        t1.Start();

        t2.Start();

        t3.Start();


        Console.ReadKey();

    }


    // each thread while at work

    static void Working() {

        // write the log operation simulation 1000

        for (int i = 0; i < 1000; i++) {

            Logger.Write(Thread.CurrentThread.Name + " writes a log: " + i + ", on " + DateTime.Now.ToString() + ".\n");

        } // do some other events

        for (int i = 0; i < 1000; i++) { }

    }

}


Concurrency: 

Multiple users compete for the same resource (this resource can log on the server, this may be the implementation of a sql operation, you can make a file on a ftp server, etc., or is one of the global variables in the program, so we We can call this resource: global resource); 

Explanation: 

Is complicated by multiple users request the same resources when the program itself is multi-threaded or requests for the same resource when due. 

such as: 

A financial system, two people at the same total amount of money for the operation, a 10 plus a minus 100, pay attention to these two operations are performed simultaneously, and that the system does not know whether to add or subtract, and this is complicated by the problem. Alternatively, a plurality of threads simultaneously request the same resource, the resource data will inevitably lead to unsafe, A thread B modifies the data processing thread, and the thread B has modified mathematical (thread-safe) A threading.


asynchronous: 

A thread To request a resource, but this resource is being threads in B, because there is no synchronization mechanism, A thread 

Still request to this resource, A thread without waiting. 

Synchronize: 

A thread To request a resource, but this resource is being threads in B, because there is a synchronization mechanism, A thread requests 

Less, how to do, A thread can wait.


Synchronous and asynchronous: 

Obviously, the synchronization of the safest, most insurance. The asynchronous unsafe, easily lead to a deadlock, this will lead to a dead thread throughout 

Process crashes, but there is no synchronization mechanism, the performance will be improved. So for synchronous and asynchronous have to make a choice.


Guess you like

Origin blog.51cto.com/14028890/2404437