Linux-----线程操作(创建)

发布于:2025-02-10 ⋅ 阅读:(33) ⋅ 点赞:(0)

目录

 创建线程

示例: 


 创建线程

#include <pthread.h>

/**
 * 创建一个新线程
 * 
 * pthread_t *thread: 指向线程标识符的指针,线程创建成功时,用于存储新创建线程的线程标识符
 * const pthread_attr_t *attr: pthead_attr_t结构体,这个参数可以用来设置线程的属性,如优先级、栈大小等。如果不需要定制线程属性,可以传入 NULL,此时线程将采用默认属性。 
 * void *(*start_routine)(void *): 一个指向函数的指针,它定义了新线程开始执行时的入口点。这个函数必须接受一个 void * 类型的参数,并返回 void * 类型的结果
 * void *arg: start_routine 函数的参数,可以是一个指向任意类型数据的指针
 * return: int 线程创建结果
 *             成功 0
 *             失败 非0
 */
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine)(void *), void *arg);

示例: 

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define BUF_LEN 1024

char* buf;

/**
 * 创建两个线程,一读取终端,一个写入终端
 */
void* input_thread(void* argv) {
    int i = 0;
    while (1)
    {
        char c = fgetc(stdin);
        if (c && c != '\n') {
            buf[i++] = c;
            // 长度溢出的情况
            if (i >= BUF_LEN) {
                i = 0;
            }
        }
    }
}

void* output_thread(void* argv) {
    int i = 0;
    while (1)
    {
        if (buf[i]) {
            // 读取一个字节写出到控制台,之后换行
            fputc(buf[i], stdout);
            buf[i++] = 0;
            // 长度溢出的情况
            if (i >= BUF_LEN) {
                i = 0;
            }
        }
        else {
            sleep(1);
        }
    } 
}

int main(int argc, char const* argv[])
{
    buf = (char*)malloc(BUF_LEN);
    for (int i = 0; i < BUF_LEN; i++)
    {
        buf[i] = 0;
    }

    // 声明线程pid
    pthread_t pid_input;
    pthread_t pid_output;

    // 创建读线程
    pthread_create(&pid_input, NULL, input_thread, NULL);
    // 创建写线程
    pthread_create(&pid_output, NULL, output_thread, NULL);

    // 主线程等待读写线程结束
    pthread_join(pid_input, NULL);
    pthread_join(pid_output, NULL);
    free(buf);
    return 0;
}


网站公告

今日签到

点亮在社区的每一天
去签到