What is a thread?

Source: Internet
Author: User
Tags thread

What is a thread.

A thread is an entity of a process that is the basic unit of CPU dispatch and dispatch, which is a smaller unit that can run independently than a process. The thread itself does not own the system resources, it has only a few resources (such as program counters, a set of registers and stacks) that are essential in the run, but it can share all the resources owned by the process with other threads belonging to one process.

Second, when to use multithreading. When multiple tasks can be executed in parallel, you can start a thread for each task.
Third, the thread is created using the Pthread_create function.

1 2 3) 4 5 #include <pthread.h> int pthread_create (pthread_t *__restrict __newthread,//newly created thread ID __const pthread_                attr_t *__restrict __attr,//thread attribute void * (*__start_routine) (void *),//The newly created thread starts from Start_routine execution void *__restrict __arg)//Parameters of the execution function

Return value: Success-0, failure-returns error number, can be used strerror (errno) function to get error message
Iv. thread termination Three ways the thread returns from the execution function, the return value is the thread's exit code thread is canceled by another thread of the same process calling the Pthread_exit () function to exit. This is not called exit, because the thread calls the Exit function, which causes the process of the thread to exit.

A small example:

Start two threads, one thread performs a 1 operation on the global variable num, executes 500 times, a thread performs a minus 1 operation on the global variable, and executes 500 times.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

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.