Home Operation and Maintenance Linux Operation and Maintenance Does Linux have a function to create threads?

Does Linux have a function to create threads?

Mar 25, 2022 pm 04:00 PM
linux Create thread

Linux has a function to create threads, namely the "pthread_create()" function. This function is a function that creates threads in Unix-like operating systems. It supports four parameters: parameter 1 is a pointer to the thread identifier, parameter 2 is used to set thread attributes, parameter 3 is the starting address of the thread running function, and parameter 4 is Parameters to run the function.

Does Linux have a function to create threads?

#The operating environment of this tutorial: linux5.9.8 system, Dell G3 computer.

Linux has a function to create threads, which is the pthread_create() function.

pthread_create() is a function that creates threads in Unix-like operating systems (Unix, Linux, Mac OS X, etc.)

Header file

 # include<pthread.h>

Function declaration

int pthread_create(
    pthread_t *restrict tidp,   //新创建的线程ID指向的内存单元。
    const pthread_attr_t *restrict attr,  //线程属性,默认为NULL
    void *(*start_rtn)(void *), //新创建的线程从start_rtn函数的地址开始运行
    void *restrict arg //默认为NULL。上述函数需要参数,将参数放入结构中并将地址作为arg传入。
    );
Copy after login

Return value

  • ##If successful, return 0, otherwise return error number

Parameters

  • The first parameter is a pointer to the thread identifier.

  • The second parameter is used to set thread attributes.

  • The third parameter is the address of the thread running function.

  • The last parameter is the parameter to run the function.

Note

Pay attention to adding the -lpthread parameter when compiling to call the static link library. Because pthread is not the default library for Linux systems.

Function usage

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <vector>
#include "main.h"

using namespace std;

struct Sample {
    uint32_t index;
    char sex;
    uint32_t age;
    uint32_t result;
};

void* TaskEntry(void *args)
{
    Sample *sa = (Sample*)args;
    uint32_t num = sa->index;
    if (num == 0) {
        printf("TaskEntry entry num = 0\n");  // 线程1执行体
        sleep(10);
        printf("TaskEntry entry num = 0 is over!!!\n");
    } else if (num == 1) {
        printf("TaskEntry entry num = 1\n");  // 线程2执行体
        sleep(10);
        printf("TaskEntry entry num = 1 is over!!!\n");
    } else if (num == 2) {
        printf("TaskEntry entry num = 2\n");  // 线程3执行体
        sleep(2);
        printf("TaskEntry entry num = 2 is over!!!\n");
    }
}

uint32_t CreateTask(pthread_t& pid, Sample& sample)
{
    // 假设Sample.index == 2创建任务失败,直接返回
    if (sample.index == 2) {
        return 2;
    }
    pthread_attr_t  attr;  // 设置线程属性
    pthread_attr_init(&attr);
    pthread_attr_setstacksize(&attr, 64 * 1024);  // 设置线程栈大小为64KB
    uint32_t ret = pthread_create(&pid, &attr, (void*(*)(void*))TaskEntry, (void*)&sample);
    if (ret != 0) {
        return ret;
    }
    pthread_attr_destroy(&attr); // 取消线程的设置属性
    return 0;
}

void VerifyTask(vector<pthread_t>& taskID, vector<Sample>& taskArgs)
{
    void *ret;
    for (int index = 0; index<2; index++) {
        // 等待线程结束,释放相应的资源。pthread_join会堵塞主线程不会堵塞其他子线程,然后等待监控的线程执行完成,再返回主线程
        // 在此处线程执行顺序为:线程1--主线程--线程2--主线程--线程3
        pthread_join(taskID[index], &ret);  // 堵塞主线程,执行子线程taskID[index],等待子线程taskID[index]执行完成释放资源
        printf("task[%d] is over\n", index);  // 主线程执行打印操作
    }
}

int main(void)
{
    // 创建3个线程
    vector<pthread_t> taskID(3);
    vector<Sample> taskArgs(3);
    for (int i = 0; i < 3; i++) {
        taskArgs[i] = { i, &#39;a&#39;, 90, 0};
        uint32_t ret = CreateTask(taskID[i], taskArgs[i]);
        if (ret != 0) {
            // 模拟如下场景:任务创建失败,直接停止前面的任务
            for (int j = 0; j<i; j++) {
                pthread_cancel(taskID[j]); // 子线程1和子线程2延迟10s,当线程3创建失败时,直接让其停止。
            }
            //return ret;  // 主线程退出,所有子线程一起退出
        }
    }
    VerifyTask(taskID, taskArgs); // 校验线程是否结束
    printf("three thead is running over!!!\n");
    return 0;
}
Copy after login
Note that when using compilation, you need to add the compilation option -lpthread, for example: g -lpthread main.cpp -o main

Related recommendations: "

Linux Video Tutorial"

The above is the detailed content of Does Linux have a function to create threads?. 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)

What computer configuration is required for vscode What computer configuration is required for vscode Apr 15, 2025 pm 09:48 PM

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

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.

vscode cannot install extension vscode cannot install extension Apr 15, 2025 pm 07:18 PM

The reasons for the installation of VS Code extensions may be: network instability, insufficient permissions, system compatibility issues, VS Code version is too old, antivirus software or firewall interference. By checking network connections, permissions, log files, updating VS Code, disabling security software, and restarting VS Code or computers, you can gradually troubleshoot and resolve issues.

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.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

How to use VSCode How to use VSCode Apr 15, 2025 pm 11:21 PM

Visual Studio Code (VSCode) is a cross-platform, open source and free code editor developed by Microsoft. It is known for its lightweight, scalability and support for a wide range of programming languages. To install VSCode, please visit the official website to download and run the installer. When using VSCode, you can create new projects, edit code, debug code, navigate projects, expand VSCode, and manage settings. VSCode is available for Windows, macOS, and Linux, supports multiple programming languages ​​and provides various extensions through Marketplace. Its advantages include lightweight, scalability, extensive language support, rich features and version

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.

See all articles