Java Learning: What is a thread? The most detailed explanation

Source: Internet
Author: User
Tags mutex semaphore
What is a thread: Sometimes it is also a lightweight process, which is the smallest unit of program execution flow.

A standard thread consists of a thread ID, a current instruction pointer (PC), a collection of registers, and a stack.

A process consists of one to multiple threads, the memory space (including code snippets, the heap of data segments, etc.) shared between each thread, and some process-level resources (such as open files and signals)

Multiple threads can perform concurrently with each other and share the process's global variables and heap data;

Access Permissions for Threads

Access to the thread is very free and can access all the data in the process memory;

Thread Scheduling and prioritization

Single-processor multi-threaded: The operating system lets these multithreading take turns, performing only a short period of time (typically a few 10 seconds), so that each thread "looks" as if it were executing simultaneously;

Three states in thread scheduling:

( 1 ): Run, at which time the thread is running

( 2 ): Ready, at which point the thread can run immediately, but CPU has been occupied

( 3 ): Wait, at which point the thread is waiting for an event to occur and cannot execute

Whenever a program leaves the running state, the dispatch system chooses a ready thread to run, and a thread event that waits for the state to enter the ready state after it occurs.

In the case of priority scheduling, there are generally three ways to change the priority of a thread:

User-specified priority;

Increase or decrease the priority according to the frequency of entering the waiting state;

Priority is promoted for long periods of time without execution;

Multithreading for Linux

Under Linux, you can create a new task with the following three methods:

(1) Fork: Copy the current process

(2) Exec: Overwrite the current executable image with a new executable image

(3) Clone: Creates a child process and executes from the specified position;

Fork

pid_t pid;

if (Pid==fork ()) {...}

After the fork call, the new task starts and returns with this task from the fork function, but the difference is that the fork of the task returns the PID of the new task, and the fork of the new task returns 0;

Fork creates a new task very quickly, because the fork does not replicate the memory space of the original task, but instead shares a write-time copy of the memory space with the original task;

so-called write-time copy : Refers to two tasks can be free to read memory at the same time, but any task attempts to modify memory, the memory will be copied to provide the modified party alone, so as not to affect the use of other tasks;

The fork can only produce a mirror of this task, so you must use EXEC mates to start another new task, and exec can replace the current executable image with a new executable image, so after the fork has created a new task, A new task can call exec to execute a new executable file;

Header files are defined in Pthread.h

Create a thread: #include <pthread.h>

int pthread_create (pthread_t *thread,const pthread_attr_t* attr,void* (*start_routine) (void*), Void*arg)

The thread parameter is the identifier for the new thread, and the subsequent pthread_* function uses it to refer to the new thread;

The attr parameter is used to set the properties of the new thread, passing null to it to indicate the use of the default thread property;

The Start_routine and ARG parameters respectively define the functions and parameters that the new thread will run;

Pthread_create returns 0 on success and returns an error code on failure;

End a thread: void Pthread_exit (void *retval)

The function passes its exit information to the thread's recycler through the retval parameter;

Thread Safety:

Multi-threaded programs in a volatile environment, accessible global variables and heap data can be changed at any time by other threads;

means: Sync and lock

Atomic: A single instruction operation is called an atom, in any case, the execution of an instruction is not interrupted;

In order to avoid the unpredictable consequences of multiple threads reading and writing data at the same time, we want to synchronize the access of each thread to the same data (so-called synchronization, that is, when one thread accesses the data is not finished, other threads must not access the same data), therefore, the access to the data is atomized;

Common Methods of synchronization: (Semaphore, mutex, critical section, read-write lock, condition variable)

Lock: Each thread accesses data or resources first to attempt to acquire a lock and release the lock after the end of the visit;

Semaphore: When a thread accesses a resource, it gets the semaphore first;

The operation is as follows:

(1) Reduce the value of the semaphore by 1;

(2) If the value of the semaphore is less than 0, it enters the waiting state;

After accessing the resource, the thread releases the semaphore;

(3) The value of the semaphore is added 1;

(4) If the value of the semaphore is less than 1, wake up a waiting thread;

Mutex Amount && Signal Volume

Same: Resource only allows one thread access at a time;

XOR: The semaphore can be obtained and released by any thread in the whole system, that is, the same semaphore can be obtained by one thread in the system, and another thread is released;

While the mutex requires which thread acquires the mutex, which thread is responsible for releasing the lock, the other thread someone else to release the mutex is invalid;

Critical Zone: A more rigorous synchronization method than a mutex

The acquisition of the lock in the critical section is called entering the critical zone;

And the release of the lock is called leaving the critical section.

Differences (with semaphores and mutexes)

Mutexes and semaphores are visible in any process of the system;

In other words, a process creates a mutex or semaphore, and another process attempts to acquire the lock is legal;

The scope of the critical section is limited to this process, and other processes cannot acquire the lock

Read/write Lock:

Two ways: Shared exclusive

When a lock is in a free state, an attempt to acquire a lock in any way succeeds and the lock is placed in the corresponding state;

condition variables: as a means of synchronization, acting like a fence;

For a condition variable, the thread has two operations:

(1) The first thread can wait for a condition variable, and a condition variable can be waited by multiple threads;

(2) A thread can wake up a condition variable, and one or all of the threads waiting for the condition variable will wake up and continue to support it;

(That is, using a condition variable allows many eng to wait for an event to occur together, and all threads can resume execution together when the event occurs).

Related articles:

What is a process? What is a thread?

Multi-Threading Implementation method based on Java learning

Related Article

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.