C语言 线程

基础

  1. 线程除了内存中的栈区不共享,其他的都共享(因为线程本质就是执行一个函数)
  2. 如果只有一个cpu多线程是无用的,因为同一时间一个进程只能获得一个cpu
  3. light weight process 轻量级的进程,本质仍是进程
    线程:最小的执行单位,有PCB,但没有地址空间(共享进程的)
    进程:最小分配资源单位,可看成是只有一个线程的进程。有PCB,有独立的地址空间
    ps –Lf pid 查看多线程进程

线程与进程

进程线程
forkpthread_create
exitpthread_exit
waitpthread_join
killpthread_cancel
getpidpthread_self

线程属性

属性描述
intetachstate; //线程的分离状态
intschedpolicy; //线程调度策略
struct sched_paramschedparam; //线程的调度参数
intinheritsched; //线程的继承性
intscope; //线程的作用域
size_tguardsize; //线程栈末尾的警戒缓冲区大小
intstackaddr_set; //线程的栈设置
void*stackaddr; //线程栈的位置
size_tstacksize; //线程栈的大小
下面是一个使用C语言线程邮箱的代码示例: ```c #include <stdio.h> #include <stdlib.h> #include <pthread.h> #define QUEUE_SIZE 10 // 队列结构体定义 typedef struct { int data[QUEUE_SIZE]; int front; int rear; pthread_mutex_t lock; pthread_cond_t not_empty; pthread_cond_t not_full; } Queue; // 初始化队列 void initQueue(Queue *q) { q->front = 0; q->rear = 0; pthread_mutex_init(&q->lock, NULL); pthread_cond_init(&q->not_empty, NULL); pthread_cond_init(&q->not_full, NULL); } // 判断队列是否已满 int isQueueFull(Queue *q) { return ((q->rear + 1) % QUEUE_SIZE == q->front); } // 判断队列是否为空 int isQueueEmpty(Queue *q) { return (q->front == q->rear); } // 入队 int enQueue(Queue *q, int data) { pthread_mutex_lock(&q->lock); while (isQueueFull(q)) { // 如果队列已满,等待 pthread_cond_wait(&q->not_full, &q->lock); } q->data[q->rear] = data; q->rear = (q->rear + 1) % QUEUE_SIZE; pthread_cond_signal(&q->not_empty); pthread_mutex_unlock(&q->lock); return 0; } // 出队 int deQueue(Queue *q, int *data) { pthread_mutex_lock(&q->lock); while (isQueueEmpty(q)) { // 如果队列为空,等待 pthread_cond_wait(&q->not_empty, &q->lock); } *data = q->data[q->front]; q->front = (q->front + 1) % QUEUE_SIZE; pthread_cond_signal(&q->not_full); pthread_mutex_unlock(&q->lock); return 0; } // 生产者线程函数 void* producer(void *arg) { Queue *q = (Queue*)arg; int i; for (i = 0; i < 20; i++) { enQueue(q, i); printf("Producer: %d\n", i); } return NULL; } // 消费者线程函数 void* consumer(void *arg) { Queue *q = (Queue*)arg; int data; while (1) { deQueue(q, &data); printf("Consumer: %d\n", data); } return NULL; } int main() { Queue q; initQueue(&q); pthread_t prod_tid, cons_tid; pthread_create(&prod_tid, NULL, producer, &q); pthread_create(&cons_tid, NULL, consumer, &q); pthread_join(prod_tid, NULL); pthread_join(cons_tid, NULL); return 0; } ``` 在以上代码中,我们使用了线程安全的队列结构体,并使用互斥锁和条件变量来实现线程同步。在生产者线程函数中,我们不断向队列中写入数据,如果队列已满,则等待条件变量 `not_full`;在消费者线程函数中,我们不断从队列中读取数据,如果队列已空,则等待条件变量 `not_empty`。 在主函数中,我们创建了一个生产者线程和一个消费者线程,并分别传入队列结构体的指针作为参数。最后,我们使用 `pthread_join` 函数等待两个子线程结束。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值