What is multithreading? What is a lock? What is the amount of information? And their respective uses, multi-thread Information

Source: Internet
Author: User

What is multithreading? What is a lock? What is the amount of information? And their respective uses, multi-thread Information

Thread concept:

  • Every program running on the system is a process. Each process contains one or more threads. The process may also be a dynamic execution of the entire program or some programs. A thread is a set of commands or special segments of a program. It can be executed independently in the program. It can also be understood as the context of code execution. Therefore, a thread is basically a Lightweight Process, which is responsible for executing multiple tasks in a single program. Generally, the operating system is responsible for scheduling and execution of multiple threads.
  • A thread is a single sequential control process in a program. multiple threads run in a single program at the same time to complete different tasks, called multithreading.
  • The difference between a thread and a process is that the child process and the parent process have different code and data spaces, while multiple threads share the data space, each thread has its own execution stack and program counter for its execution context. multithreading is mainly used to save CPU time and make full use of it, depending on the specific situation. the computer's memory resources and CPU need to be used during thread running.

Concept of Multithreading

  • Multithreading refers to the technology for implementing concurrent execution of multiple threads on software or hardware.
  • Multithreading is used to synchronize multiple tasks, not to improve the running efficiency, but to improve the resource usage efficiency to improve the system efficiency. The thread is implemented when multiple tasks need to be completed at the same time.
  • The simplest analogy is that multithreading is like every carriage of a train, and the process is a train. When a carriage leaves a train, it cannot run. Similarly, a train cannot only run one carriage. Multithreading is designed to improve efficiency.

If your application requires the following operations, you can consider the multithreading mechanism during programming:

  • Continuous operations can take a long time to complete.
  • Parallel Computing
  • It takes a lot of time to wait for the network, file system, user, or other I/O responses
  • Therefore, make sure that the preceding three situations exist in your application before you start.

Why multithreading is required (explain when to consider using threads)

  • From the user's perspective, it is to get better system services; from the perspective of the program itself, it is to make the target task as quickly as possible to make more effective use of system resources. Generally, multithreading is required in the following scenarios:
  • When a program contains complex computing tasks, it mainly uses multithreading to obtain more CPU time (resources ).
  • Peripheral devices with slow processing speed, such as printing. For another example, network programs involve packet sending and receiving. The time is variable. Using Independent threads to process these tasks does not require the program to wait for results.
  • The WINDOWS System is a preemptible multi-task System Based on the message loop. To prevent the message loop system from being congested, the program needs multiple threads to complete some tasks together.
  • Every program running on the system is a process. Each process contains one or more threads. The process may also be a dynamic execution of the entire program or some programs. A thread is a set of commands or special segments of a program. It can be executed independently in the program. It can also be understood as the context of code execution. Therefore, a thread is basically a Lightweight Process, which is responsible for executing multiple tasks in a single program. Generally, the operating system is responsible for scheduling and execution of multiple threads.

Thread priority

  • The value of priority is 1-10 (the higher the value, the higher the priority ).
  • Public final int getPriority (); returns the value of the thread priority.
  • Public final void setPriority (int newPriority); modifies the priority of a thread.
  • Note: A high priority does not mean that the thread must run first, but only indicates that the thread runs first.

Common methods for controlling thread cycles

  • Wait () releases the execution right of the CPU and releases the lock.
  • Y () is returned to the status before wait.
  • Yied () temporarily suspends the thread. (Let the thread release the resource)
  • Join () forces the thread to Join the execution.
  • SetDaemon (true) sets this thread as the background thread (when the current thread ends, the background thread will end together ).
  • Note: The thread termination principle is to end the run method, so you only need to control the run process.

Why thread synchronization?

  • Sharing code and data between threads can save system overhead and improve efficiency. But it also causes "Data Access conflict ". How to implement Organic interaction between threads and ensure that only one thread can access Shared resources at a time, that is, thread synchronization.
  • The data shared by multiple threads is called a critical resource.
Synchronization and mutex of multiple threads: Method 1: Lock
  • Initialize the lock to unlock status in the main thread
    • Pthread_mutex_t mutex;
    • Pthread_mutex_init (& mutex, NULL );
  • The initialization lock is unlocked during compilation.
    • Lock initialization pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  • Lock and unlock operations when accessing objects
    • Lock pthread_mutex_lock (& mutex)
    • Release the pthread_mutex_unlock (& mutex) Lock)

Mutex lock

  • Each object corresponds to a mutex lock tag, which ensures that only one thread can access the object at a certain time.
  • The key word synchronized of the mutex lock can be written on a method (the object that the lock calls this method). It can be included in the statement to be locked.
  • Benefits: solved the thread security issue.
  • Disadvantages: it reduces the running efficiency (judge the lock and cannot share information); it is prone to deadlock.

Deadlock:

  • Two threads A and B use the same object s (s is A shared resource), and thread A needs to create conditions after B is run during execution. Under this premise, A starts to run. after entering the synchronization block, the object s is locked. Then thread A enters the blocking state after waiting for the end of thread B, so thread B starts to run, but because the object s cannot be accessed, thread B also enters the blocking state, waiting for thread A to unlock s. Final Result: both threads wait for each other and cannot run.

Method 2: semaphores

The lock has an obvious drawback, that is, itThere are only two statuses: Locked or not locked.

Semaphores are essentially a non-negative integer counter, which is also used to control access to public resources. When the public resources increase, call the sem_post () function to increase the semaphores. When the public resources decrease, call the sem_wait () function to reduce the semaphores. In fact, we can regard the lock as a 0-1 semaphore.

They are in/usr/include/semaphore.hThe data structure of the semaphore is sem_t. Essentially, it is a long integer.

Related functions

Before using semaphore, we need to introduce the header file first.#include <semaphore.h>

  • Initial semaphores:int sem_init(sem_t *sem, int pshared, unsigned int value);
    • 0 is returned for success and-1 is returned for failure.
    • Parameters
    • Sem: a pointer to the semaphore Structure
    • Pshared: When the value is not 0, the semaphore is shared among processes. Otherwise, it can only be shared by all threads of the current process.
    • Value: the initial value of the semaphore.
  • Semaphores minus 1. When sem = 0, this function will be blocked.int sem_wait(sem_t *sem);
    • 0 is returned for success and-1 is returned for failure.
    • Parameters
    • Sem: a pointer to the semaphore
  • Semaphore plus 1 Operationint sem_post(sem_t *sem);
    • The same is true for parameters and responses.
  • Destroy semaphoresint sem_destroy(sem_t *sem);
    • The same is true for parameters and responses.

Differences between semaphores and locks

Semaphores are used for multi-thread and multi-task synchronization. When a thread completes an action, it tells other threads through semaphores that other threads perform some actions (when everyone is in the semtake, ). The mutex lock is used for multi-thread multi-task mutex. If a thread occupies a certain resource, other threads cannot access it until the thread is unlocked, other threads can use this resource. For example, you may need to lock the access to global variables. After the operation is complete, you must unlock the global variables. Sometimes the lock and semaphore will be used at the same time"

That is to say, semaphores do not necessarily lock A certain resource, but are the concept of A process. For example, there are two threads A and B, thread B must wait for thread A to complete A task and then perform the following steps. This task does not necessarily lock A certain resource, or perform some computing or data processing. The thread mutex is the concept of "locking a resource". During the lock period, other threads cannot perform operations on the protected data. In some cases, the two are interchangeable.

Differences between the two:

Scope

Semaphores: processes or threads (Linux is only an unknown semaphores between threads pthread semaphore)

Mutex lock: between threads

Lock

Semaphores: as long as the semaphores value is greater than 0, other threads can successfully sem_wait, And the semaphores value minus one after success. If the value is not greater than 0, sem_wait blocks the thread until the value of sem_post is increased by one after it is released, but sem_wait will still reduce the value by one before it returns.

Mutex lock: as long as it is locked, no other thread can access protected resources

The following are some concepts about traffic signals:

The main difference between a traffic signal and a mutex lock and a condition variable lies in the concept of a "lamp". When a lamp is on, resources are available, and when the lamp is off, the lights are unavailable. If the synchronization mode in the last two phases focuses on "Waiting" operations, that is, if the resource source is unavailable, the traffic signal mechanism focuses on lighting, that is, to inform the resource availability;

It makes no sense to unlock a thread without waiting for it or to stimulate the conditions. The lighting operation of a thread without waiting for it is effective and can be kept on. Of course, such operation primitives also mean more overhead.

In addition to the binary lamp, the application of traffic signals can also use a lamp number greater than 1 to indicate that the number of resources is greater than 1.

Atomic operation

When multi-process (thread) accesses shared resources, it can ensure that all other processes (threads) access the same resources at the same time. Atomic operation does not require synchronized, which is a common topic in Java multi-thread programming. The so-called atomic operation is an operation that will not be interrupted by the thread scheduling mechanism. Once this operation starts, it will continue to run until the end, and there will be no context switch (switch to another thread) in the middle ). Generally speaking, atomic operations include assigning values to non-long and double primitive values, and returning primitive values other than the two. The reason why we need to exclude them is that they are both relatively large, and the JVM design specification does not require read operations and value assignment operations to be atomic operations (JVM can try to do this, but not guaranteed ).

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.