完成量:线程同步

作用:一个线程发送信号通知另一个线程开始执行某个任务
#include <linux/completion.h>

struct completion{
unsigned int done;
wait_queue_head_t wait;
}

done
0:等待 >0:可执行
wait 等待队列

定义和初始化完成量
定义
struct completion com;

初始化init_completion
static inline void init_completion(struct completion *x)
{
x->done = 0;
init_waitqueue_head(&x->wait);
}

等待完成量 wait_for_completion
void __sched wait_for_completion(struct completion *x) 不可打断

释放完成量
void complete(struct completion *x) 只唤醒一个等待进程或者线程
void complete_all(struct completion *x) 释放所有完成量,唤醒所有等待的进程或者线程

使用:
struct completion com;

inti_completion(&com)

线程A:
wait_for_completion(&com)

线程B:
complete(&com)





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在多线程编程中,为了防止多个线程同时访问共享资源而导致的数据竞争问题,需要使用同步机制来实现线程间的协调和互斥。而互斥是一种常用的同步机制,在多线程编程中被广泛使用。 互斥是一种线同步原语,用于保护共享资源。当一个线程需要访问共享资源时,它需要先获取该资源的互斥。如果该互斥已经被其他线程占用,则当前线程会被阻塞,直到该互斥被释放。一旦该互斥被释放,当前线程就可以获取该互斥,访问共享资源,并将该互斥加锁。当该线完成对共享资源的访问后,它需要将该互斥解锁,以便其他线程可以获取该互斥继续访问共享资源。 互斥的使用一般涉及到以下四个函数: 1. pthread_mutex_init():初始化互斥; 2. pthread_mutex_lock():加锁互斥; 3. pthread_mutex_unlock():解锁互斥; 4. pthread_mutex_destroy():销毁互斥。 下面是一个简单的例子,展示了如何使用互斥实现线同步: ``` #include <stdio.h> #include <pthread.h> pthread_mutex_t mutex; // 定义互斥 void *thread_func(void *arg) { pthread_mutex_lock(&mutex); // 加锁互斥 printf("Thread %ld is running.\n", pthread_self()); pthread_mutex_unlock(&mutex); // 解锁互斥 pthread_exit(NULL); } int main(int argc, char *argv[]) { pthread_t t1, t2; pthread_mutex_init(&mutex, NULL); // 初始化互斥 pthread_create(&t1, NULL, thread_func, NULL); pthread_create(&t2, NULL, thread_func, NULL); pthread_join(t1, NULL); pthread_join(t2, NULL); pthread_mutex_destroy(&mutex); // 销毁互斥 return 0; } ``` 在上面的例子中,我们定义了一个互斥 mutex,然后在线程函数中分别加锁和解锁该互斥。在主函数中,我们创建了两个线程,并等待它们执行完毕后退出程序。需要注意的是,我们必须在程序退出之前销毁该互斥,以免产生内存泄漏。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值