


Let’s take an example first. We create two threads to increment a number. Maybe this example has no practical value, but with a slight change, we can use it in other places.
Code:
/*thread_example.c : c multiple thread programming in linux *author : falcon *e-mail : tunzhj03@st.lzu.edu.cn */ #include <pthread.h> #include <stdio.h> #include <sys/time.h> #include <string.h> #define max 10 pthread_t thread[2]; pthread_mutex_t mut; int number=0, i; void *thread1() { printf ("thread1 : i'm thread 1/n"); for (i = 0; i < max; i++) { printf("thread1 : number = %d/n",number); pthread_mutex_lock(&mut); number++; pthread_mutex_unlock(&mut); sleep(2); } printf("thread1 :主函数在等我完成任务吗?/n"); pthread_exit(null); } void *thread2() { printf("thread2 : i'm thread 2/n"); for (i = 0; i < max; i++) { printf("thread2 : number = %d/n",number); pthread_mutex_lock(&mut); number++; pthread_mutex_unlock(&mut); sleep(3); } printf("thread2 :主函数在等我完成任务吗?/n"); pthread_exit(null); } void thread_create(void) { int temp; memset(&thread, 0, sizeof(thread)); //comment1 /*创建线程*/ if((temp = pthread_create(&thread[0], null, thread1, null)) != 0) //comment2 printf("线程1创建失败!/n"); else printf("线程1被创建/n"); if((temp = pthread_create(&thread[1], null, thread2, null)) != 0) //comment3 printf("线程2创建失败"); else printf("线程2被创建/n"); } void thread_wait(void) { /*等待线程结束*/ if(thread[0] !=0) { //comment4 pthread_join(thread[0],null); printf("线程1已经结束/n"); } if(thread[1] !=0) { //comment5 pthread_join(thread[1],null); printf("线程2已经结束/n"); } } int main() { /*用默认属性初始化互斥锁*/ pthread_mutex_init(&mut,null); printf("我是主函数哦,我正在创建线程,呵呵/n"); thread_create(); printf("我是主函数哦,我正在等待线程完成任务阿,呵呵/n"); thread_wait(); return 0; }
Let’s compile and execute it first
Quotation:
falcon@falcon:~/program/c/code/ftp$ gcc -lpthread -o thread_example thread_example.c falcon@falcon:~/program/c/code/ftp$ ./thread_example 我是主函数哦,我正在创建线程,呵呵 线程1被创建 线程2被创建 我是主函数哦,我正在等待线程完成任务阿,呵呵 thread1 : i'm thread 1 thread1 : number = 0 thread2 : i'm thread 2 thread2 : number = 1 thread1 : number = 2 thread2 : number = 3 thread1 : number = 4 thread2 : number = 5 thread1 : number = 6 thread1 : number = 7 thread2 : number = 8 thread1 : number = 9 thread2 : number = 10 thread1 :主函数在等我完成任务吗? 线程1已经结束 thread2 :主函数在等我完成任务吗? 线程2已经结束
The comments in the example code should be clearer, below I have quoted several functions and variables mentioned above on the Internet.
Citation:
Thread related operations
一pthread_t
pthread_t is defined in the header file /usr/include/bits/pthreadtypes.h:
Typedef unsigned long int pthread_t;
It is the identifier of a thread.
二pthread_create
The function pthread_create is used to create a thread. Its prototype is:
extern int pthread_create __p ((pthread_t *__thread, __const pthread_attr_t *__attr,
void * (*__start_routine) (void *), void *__arg));
The first parameter is a pointer to the thread identifier, the second parameter is used to set the thread attributes, and the third parameter is the start of the thread running function. The starting address, the last parameter is the parameter to run the function. Here, our function thread does not require parameters, so the last parameter is set to a null pointer. We also set the second parameter to a null pointer, which will generate a thread with default attributes. We will explain the setting and modification of thread attributes in the next section. When the thread is created successfully, the function returns 0. If it is not 0, the thread creation fails. Common error return codes are eagain and einval. The former means that the system restricts the creation of new threads, for example, the number of threads is too many; the latter means that the thread attribute value represented by the second parameter is illegal. After the thread is successfully created, the newly created thread runs the function determined by parameter three and parameter four, and the original thread continues to run the next line of code.
Three pthread_join pthread_exit
The function pthread_join is used to wait for the end of a thread. The function prototype is:
extern int pthread_join __p ((pthread_t __th, void **__thread_return));
The first parameter is the thread identifier to be waited for, and the second parameter is a user-defined pointer. Can be used to store the return value of the waiting thread. This function is a thread-blocking function. The function calling it will wait until the waiting thread ends. When the function returns, the resources of the waiting thread are recovered. There are two ways to end a thread. One is like our example above. When the function ends, the thread that called it also ends. The other way is through the function pthread_exit. Its function prototype is:
extern void pthread_exit __p ((void *__retval)) __attribute__ ((__noreturn__));
The only parameter is the return code of the function, as long as the second parameter thread_return in pthread_join is not null , this value will be passed to thread_return. The last thing to note is that a thread cannot be waited by multiple threads, otherwise the first thread that receives the signal returns successfully, and the remaining threads that call pthread_join return the error code esrch.
In this section, we wrote the simplest thread and mastered the three most commonly used functions pthread_create, pthread_join and pthread_exit. Next, let's take a look at some common properties of threads and how to set them.
Mutex lock related
Mutex lock is used to ensure that only one thread is executing a piece of code within a period of time.
一pthread_mutex_init
The function pthread_mutex_init is used to generate a mutex lock. The null parameter indicates that the default properties are used. If you need to declare a mutex for a specific attribute, you must call the function pthread_mutexattr_init. The function pthread_mutexattr_setpshared and the function pthread_mutexattr_settype are used to set the mutex lock attributes. The previous function sets the attribute pshared, which has two values, pthread_process_private and pthread_process_shared. The former is used to synchronize threads in different processes, and the latter is used to synchronize different threads in this process. In the above example, we are using the default attribute pthread_process_private. The latter is used to set the mutex lock type. The optional types are pthread_mutex_normal, pthread_mutex_errorcheck, pthread_mutex_recursive and pthread _mutex_default. They respectively define different listing and unlocking mechanisms. Under normal circumstances, the last default attribute is selected.
2 pthread_mutex_lock pthread_mutex_unlock pthread_delay_np
The pthread_mutex_lock statement starts to lock with a mutex lock. The subsequent code is locked until pthread_mutex_unlock is called, that is, it can only be called and executed by one thread at the same time. When a thread executes to pthread_mutex_lock, if the lock is used by another thread at this time, the thread is blocked, that is, the program will wait until another thread releases the mutex lock.
Notice:
1 It should be noted that the above two sleeps are not only for demonstration purposes, but also to let the thread sleep for a period of time, let the thread release the mutex lock, and wait for another thread to use this lock. This problem is explained in Reference 1 below. However, there seems to be no pthread_delay_np function under Linux (I tried it and it was prompted that there is no reference to the function defined), so I used sleep instead. However, another method is given in Reference 2, which seems to be replaced by pthread_cond_timedwait. , which gives a way to achieve it.
2 Please pay attention to the comments1-5 inside, that is where the problem took me several hours to find out.
If there are no comment1, comment4, and comment5, it will cause a segfault during pthread_join. In addition, the above comment2 and comment3 are the root cause, so be sure to remember to write the entire code. Because the above thread may not be created successfully, it is impossible to wait for the thread to end, and a segmentation fault occurs (an unknown memory area is accessed) when using pthread_join. In addition, when using memset, you need to include the string.h header file
The above is the detailed content of Linux multi-threaded programming example code analysis. For more information, please follow other related articles on the PHP Chinese website!

The five core components of the Linux operating system are: 1. Kernel, 2. System libraries, 3. System tools, 4. System services, 5. File system. These components work together to ensure the stable and efficient operation of the system, and together form a powerful and flexible operating system.

The five core elements of Linux are: 1. Kernel, 2. Command line interface, 3. File system, 4. Package management, 5. Community and open source. Together, these elements define the nature and functionality of Linux.

Linux user management and security can be achieved through the following steps: 1. Create users and groups, using commands such as sudouseradd-m-gdevelopers-s/bin/bashjohn. 2. Bulkly create users and set password policies, using the for loop and chpasswd commands. 3. Check and fix common errors, home directory and shell settings. 4. Implement best practices such as strong cryptographic policies, regular audits and the principle of minimum authority. 5. Optimize performance, use sudo and adjust PAM module configuration. Through these methods, users can be effectively managed and system security can be improved.

The core operations of Linux file system and process management include file system management and process control. 1) File system operations include creating, deleting, copying and moving files or directories, using commands such as mkdir, rmdir, cp and mv. 2) Process management involves starting, monitoring and killing processes, using commands such as ./my_script.sh&, top and kill.

Shell scripts are powerful tools for automated execution of commands in Linux systems. 1) The shell script executes commands line by line through the interpreter to process variable substitution and conditional judgment. 2) The basic usage includes backup operations, such as using the tar command to back up the directory. 3) Advanced usage involves the use of functions and case statements to manage services. 4) Debugging skills include using set-x to enable debugging mode and set-e to exit when the command fails. 5) Performance optimization is recommended to avoid subshells, use arrays and optimization loops.

Linux is a Unix-based multi-user, multi-tasking operating system that emphasizes simplicity, modularity and openness. Its core functions include: file system: organized in a tree structure, supports multiple file systems such as ext4, XFS, Btrfs, and use df-T to view file system types. Process management: View the process through the ps command, manage the process using PID, involving priority settings and signal processing. Network configuration: Flexible setting of IP addresses and managing network services, and use sudoipaddradd to configure IP. These features are applied in real-life operations through basic commands and advanced script automation, improving efficiency and reducing errors.

The methods to enter Linux maintenance mode include: 1. Edit the GRUB configuration file, add "single" or "1" parameters and update the GRUB configuration; 2. Edit the startup parameters in the GRUB menu, add "single" or "1". Exit maintenance mode only requires restarting the system. With these steps, you can quickly enter maintenance mode when needed and exit safely, ensuring system stability and security.

The core components of Linux include kernel, shell, file system, process management and memory management. 1) Kernel management system resources, 2) shell provides user interaction interface, 3) file system supports multiple formats, 4) Process management is implemented through system calls such as fork, and 5) memory management uses virtual memory technology.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1
Easy-to-use and free code editor

WebStorm Mac version
Useful JavaScript development tools
