Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to create and use Linux pthread threads

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

This article introduces the knowledge of "how to create and use Linux pthread threads". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Preface

The difference between threads and processes

(1) process: the smallest unit scheduled by the operating system. Under Linux, you can view the details of the process through commands such as ps, top, etc.

(2) Thread: the smallest unit of process scheduling, each process has a main thread. The main thing to do in a process is a thread.

(3) in the whole system, the process ID is the unique identity, and the management of the process is realized through PID. Each time a process is created, the kernel creates a structure to store all the information about the process, and each node that stores the process information holds its own PID. This ID is used when the process needs to be managed (such as sending signals). When the child process ends and needs to be reclaimed (the child process calls exit () to exit or the code is finished), it needs to be called by the wait () system. The unrecycled dying process will become a zombie process, and its process entity will no longer exist, but it will occupy PID resources, so recovery is necessary.

For a thread, to actively terminate requires a call to pthread_exit (), the main thread needs to call pthread_join () to reclaim (provided that the thread does not set the "detach property"). Thread signals are also sent through thread ID.

Mode of communication between processes:

a. Shared memory B. Message queuing C. Semaphore D. The famous pipeline E. Unnamed pipeline F. Signal G. File H.socket

The mode of communication between threads:

a. The mutually exclusive quantity B. Spin lock C. Conditional variable D. Read-write lock E. Thread signal F. Global variable

The mode of communication between processes either requires switching kernel context or accessing with peripherals (named pipes, files). So the speed will be slow. If the thread uses its own unique way of communication, it is basically completed in its own process space, and there is no switching, so the communication speed will be faster. In other words, the way of communication between processes and threads is not only different in type, but also different in speed.

Note: when a process running multithreading captures a signal, it will only block the main thread and other child threads will not affect the continuation of execution.

two。 Introduction to thread-related functions

2.1 create thread

Pthread_create is a function of the Unix operating system (Unix, Linux, etc.) to create threads. You need to specify a link library at compile time:-lpthread function prototype

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

Parameter introduction

The first parameter is a pointer to the thread identifier. The second parameter is used to set thread properties. NULL can be entered by default. The third parameter is the starting address of the thread running function. The last parameter is the parameter of the running function. You can enter NULL without parameters. View function help under Linux: # man pthread_create

Return value: 0 is returned if the thread is created successfully. If thread creation fails, the error number is returned. After the thread is created successfully, the attr parameter is used to specify various thread properties. The newly created thread runs from the address of the start_rtn function, which has only one universal pointer parameter arg. If you need to pass more than one parameter to the thread's working function, you need to put these parameters into a structure, and then pass in the address of this structure as a parameter of arg.

Example:

# include # include / / Thread function 1void * pthread_func1 (void * arg) {while (1) {printf ("Thread function 1 is running.\ n"); sleep (2);}} / / Thread function 2void * pthread_func2 (void * arg) {while (1) {printf ("Thread function 2 is running.\ n"); sleep (2) }} int main (int argc,char * * argv) {pthread_t thread_id1; pthread_t thread_id2; / * 1. Create thread 1thread / if (pthread_create (& thread_id1,NULL,pthread_func1,NULL)) {printf ("Thread 1 creation failed!\ n"); return-1;} / * 2. Create thread 2thread / if (pthread_create (& thread_id2,NULL,pthread_func2,NULL)) {printf ("Thread 2 creation failed!\ n"); return-1;} / * 3. Wait for the thread to finish and release the thread's resources * / pthread_join (thread_id1,NULL); pthread_join (thread_id2,NULL); return 0;} / / gcc pthread_demo_code.c-lpthread

2.2 exit thread

A thread terminates execution by calling the pthread_exit function, just as the process calls the exit function at the end. The purpose of this function is to terminate the thread that called it and return a pointer to an object.

The purpose of this function is to terminate the thread calling it and return a pointer to an object, which can be obtained from the second argument of the pthread_join function.

Function prototype

# include void pthread_exit (void * retval)

Parameter parses the address that the thread needs to return. Note: the thread stack must be released when the thread ends, that is, the thread function must call pthread_exit () to end, otherwise it will not be released until the main process function exits.

2.3 wait for the thread to finish

The pthread_join () function waits for the end of the thread specified by thread in a blocking manner. When the function returns, the resources of the waiting thread are reclaimed. If the thread has ended, the function returns immediately. And the thread specified by thread must be a joinable (associative attribute) attribute. Function prototype

# include int pthread_join (pthread_t thread, void * * retval)

The first parameter of the parameter: the thread identifier, the thread ID, identifies the unique thread. The last parameter: a user-defined pointer that stores the address to be returned by the waiting thread. A return value of 0 indicates success. If it fails, the error number is returned. Example of return value from receiving thread:

/ / exit thread pthread_exit ("thread exited normally"); / / return value of receiving thread void * pth_join_ret1;pthread_join (thread1, & pth_join_ret1)

2.4 Thread Separation Properties

The default state of creating a thread is joinable (binding attribute). If a thread ends running but does not call pthread_join, its state is similar to the Zombie Process (dead process) in the process, that is, some resources have not been reclaimed (exit status code), so the creator of the thread should pthread_join to wait for the thread to finish running, and can get the thread's exit code to reclaim its resources (similar to the process's wait,waitpid). But after calling the pthread_join (pthread_id) function, if the thread doesn't finish running, the caller will be blocked, and in some cases we don't want that to happen.

The pthread_detach function sets the state of the thread to detached (detached state), and all resources are automatically released after the thread finishes running. Function prototype

# include int pthread_detach (pthread_t thread)

The parameter thread identifier returns a value of 0 indicating success. Error returns error code. The EINVAL thread is not a joinable thread. ESRCH has no thread ID to be discovered.

2.5 get the identifier of the current thread

The function of the pthread_self function is to get the thread's own ID. Function prototype

# include pthread_t pthread_self (void)

Returns the identifier of the current thread. The type of pthread_t is unsigned long int, so use% lu when printing, otherwise there is a problem with displaying the results.

2.6 automatically clean up thread resources

A thread can schedule the functions it needs to call when it exits. Such functions are called thread cleanup handlers. It is used to clean up the resources when the program exits abnormally. A pthread_cleanup_push () / pthread_cleanup_pop () function is provided in the POSIX thread API to automatically release resources. Termination actions (including calls to pthread_exit () and abnormal termination) in the program segment between the call point of pthread_cleanup_push () and pthread_cleanup_pop () will execute the cleanup function specified by pthread_cleanup_push ().

Note: the pthread_cleanup_push function and the pthread_cleanup_pop function need to be called in pairs. Function prototype

Void pthread_cleanup_push (void (* routine) (void *), void * arg); / / register cleanup function void pthread_cleanup_pop (int execute); / / release cleanup function

Parameter void (* routine) (void *): the function entry of the handler. Void * arg: the formal parameter passed to the handler. Int execute: the status value of the execution. 0 means that the cleanup function is not called. 1 means that the cleanup function is called.

The conditions that caused the cleanup function call:

Call the pthread_exit () function

The formal parameter of pthread_cleanup_pop is 1. Note: return does not cause cleanup function calls.

2.7 sample code for automatic cleaning of threads

# include # include # include / / Thread cleanup function void routine_func (void * arg) {printf ("Thread Resources cleaned successfully\ n");} / / Thread working function void * start_routine (void * dev) {pthread_cleanup_push (routine_func,NULL); / / terminates the thread / / pthread_exit (NULL); pthread_cleanup_pop (1); / / 1 causes the cleanup function to be called. 0 will not be called. } int main (int argc,char * argv []) {pthread_t thread_id; / / Identifier of the stored thread / * 1. Create thread * / if (pthread_create (& thread_id,NULL,start_routine,NULL)! = 0) {printf ("thread creation failed!\ n");} / * 2. Set the detach property of the thread * / if (pthread_detach (thread_id)! = 0) {printf ("failed to set the detach property!\ n");} while (1) {} return 0;}

2.8 Thread cancel function

The pthread_cancel function cancels the function for the thread and is used to cancel other threads in the same process.

Header file: # include function prototype: pthread_cancel (pthread_t tid); this is the end of "how to create and use Linux pthread threads". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report