linux 操作系统:pthread 多线程库

本文详细介绍Linux下线程的创建、线程栈大小及数量的设置,以及线程间的同步与通信机制,包括互斥量、条件变量和信号量的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、线程创建

#include <stdio.h>
#include <unistd.h>      //posix标准的unix标准接口
#include <pthread.h>

pthread_t tid1;  //线程id
pthread_t tid2;

void *fun1()     //线程函数
{
    pid_t pid = getpid();             //获取进程id
    pthread_t tid = pthread_self();   //获取线程id
    printf("fun1, pid = %d, tid = %d\n", pid, tid);  //打印函数名和线程id
    return;
}

void *fun2()     //线程函数
{
    pthread_t tid = pthread_self();   //获取线程id
    printf("fun2, tid = %d\n", tid);  //打印函数名和线程id
    return;
}

int main()
{
    int n = 10;
    pthread_create(&tid1, 0, fun1, 0);   //线程创建
    pthread_create(&tid2, 0, fun2, 0); 
    
    return 0;
}

// gcc test.c -o test -lpthread
// ./test

二、线程栈大小、线程数量

1、查看 linux 系统默认设置

(1)用来查看系统当前用户进程的各种设置。

    ulimit -a

(2)max user processer —— 设置每个用户的最大进程数量

    ulimit -u 7864
    ulimit -u 10240

(3)open file —— 设置每个进程可以打开的最大文件数目,内核可以同时打开的文件描述符的最大值

    ulimit -n 4096

(4)stack size —— 临时改变栈空间大小

    ulimit -s 8192     #即8M。

32位linux下的进程用户空间是3G,即3072M, 3072 M/8M=384个。

三、线程同步与通信

1、互斥量(mutex)

(1)创建、初始化

#include <pthread.h>

pthread_mutex_t mutex;

pthread_mutex_init(&mutex, 0);

(2)加锁、解锁

pthread_mutex_lock(&mutex);     //申请锁

pthread_mutex_trylock(&mutex);  //尝试申请锁,非阻塞轮询

pthread_mutex_unlock(&mutex);   //释放锁

2、条件变量(condition)

(1)创建、初始化

#include <pthread.h>

pthread_cond_t cond;

pthread_cond_init(&cond, 0);

(2)等待、通知

pthread_cond_wait(&cond, &mutex);   //等待

pthread_cond_timewait(&cond, &mutex); //超时等待

pthread_cond_signal(&cond);         //通知一个等待的线程

pthread_cond_broadcast(&cond);      //通知所有等待的线程

3、信号量(semaphore)

(1)创建、初始化

#include <semaphore.h>   //自己加头文件

sem_t sem;

sem_init(&sem, 0, 0);   //信号量,局部,初始值

(2)等待、释放

sem_wait(&sem);   //等待

sem_post(&sem);   //释放

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值