Home Operation and Maintenance Linux Operation and Maintenance Linux multi-threaded programming example code analysis

Linux multi-threaded programming example code analysis

May 26, 2023 pm 10:04 PM
linux

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&#39;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&#39;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;
}
Copy after login

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&#39;m thread 1
thread1 : number = 0
thread2 : i&#39;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已经结束
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1244
24
Linux Architecture: Unveiling the 5 Basic Components Linux Architecture: Unveiling the 5 Basic Components Apr 20, 2025 am 12:04 AM

The five basic components of the Linux system are: 1. Kernel, 2. System library, 3. System utilities, 4. Graphical user interface, 5. Applications. The kernel manages hardware resources, the system library provides precompiled functions, system utilities are used for system management, the GUI provides visual interaction, and applications use these components to implement functions.

How to check the warehouse address of git How to check the warehouse address of git Apr 17, 2025 pm 01:54 PM

To view the Git repository address, perform the following steps: 1. Open the command line and navigate to the repository directory; 2. Run the "git remote -v" command; 3. View the repository name in the output and its corresponding address.

vscode Previous Next Shortcut Key vscode Previous Next Shortcut Key Apr 15, 2025 pm 10:51 PM

VS Code One-step/Next step shortcut key usage: One-step (backward): Windows/Linux: Ctrl ←; macOS: Cmd ←Next step (forward): Windows/Linux: Ctrl →; macOS: Cmd →

How to run java code in notepad How to run java code in notepad Apr 16, 2025 pm 07:39 PM

Although Notepad cannot run Java code directly, it can be achieved by using other tools: using the command line compiler (javac) to generate a bytecode file (filename.class). Use the Java interpreter (java) to interpret bytecode, execute the code, and output the result.

How to run sublime after writing the code How to run sublime after writing the code Apr 16, 2025 am 08:51 AM

There are six ways to run code in Sublime: through hotkeys, menus, build systems, command lines, set default build systems, and custom build commands, and run individual files/projects by right-clicking on projects/files. The build system availability depends on the installation of Sublime Text.

What is the main purpose of Linux? What is the main purpose of Linux? Apr 16, 2025 am 12:19 AM

The main uses of Linux include: 1. Server operating system, 2. Embedded system, 3. Desktop operating system, 4. Development and testing environment. Linux excels in these areas, providing stability, security and efficient development tools.

laravel installation code laravel installation code Apr 18, 2025 pm 12:30 PM

To install Laravel, follow these steps in sequence: Install Composer (for macOS/Linux and Windows) Install Laravel Installer Create a new project Start Service Access Application (URL: http://127.0.0.1:8000) Set up the database connection (if required)

git software installation git software installation Apr 17, 2025 am 11:57 AM

Installing Git software includes the following steps: Download the installation package and run the installation package to verify the installation configuration Git installation Git Bash (Windows only)

See all articles