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 |