Create a pthread for multithreaded programming
PthreadPOSIX threads is short for POSIXThread Standard.Thread creation is the first step in multi-threaded programming. It is essential to understand the multi-threaded programming during thread creation.
1. Create a Pthread: pthread_create ()Pthread creates a thread through the thread creation function pthread_create. It is defined as follows:
Parameters:The first parameter is the thread ID pointer;Second parameter: thread attribute parameter;The third parameter is the address of the thread-running function;Fourth parameter: runtime function parameters;Today, we create a default thread without the second and fourth parameters. This section will be detailed later. The first parameter is a pointer of the pthread_t type. The prototype of the macro pthread_t is unsigned long int, which is used to store the thread ID. In the system, each thread has a uniqueThread ID, used to differentiate and manage threads. The third parameter void * (* start_function) (void *) indicates a pointer to a function whose return value is void * and Its Parameter type is void.
2. pthread_create:
- Return Value: pthread_create returns an int type value, and 0 is returned when the thread is successfully created. Other values indicate that an error occurs when the thread is created. It is easy to misunderstand that the return thread ID.
- The first parameter: pthread_t type pointer, which is essentially to pass the address of a pthread_t variable to the function. The pthread_create function writes the ID of the Creation thread to the pthread_t variable, you can obtain the thread ID through the pthread_t.
- Run immediately after the thread is created: After the pthread_create function is successfully created, the thread runs immediately.
3. pthread_create knife test:
When the mian function is running, the system automatically creates a thread called the main thread. Pass
The thread created by pthread_create is called a subthread. The program uses the Sleep function to Sleep the main thread so that the sub-thread runs the print information. Otherwise, the main thread returns 0 to end the process, and the newly created sub-thread also dies. The output of the sub-thread is not displayed on the screen.