C++信号

首先什么是信号(signal),基本可以理解成改变程序流程的一个东西

信号是一种软件中断,一种向进程传递有关其他进程,操作系统和硬件状态的信息的方法。信号是一种中断,因为它可以改变程序的流程。当信号传递给进程时,进程将停止其执行的操作,处理或忽略信号,或者在某些情况下终止,取决于信号。

几种常用信号

SIGINT 2 表示信号中断的意思

SIGILL 4主要用于检测非法指令

SIGSEGV 11表示非法访问内存

SIGTERM 15 表示发送到程序的终止请求

SIGBREAK 21 表示 信号中止,异常终止。程序提前结束

<
信号
SIGABRT (信号中止)异常终止,例如由...发起 退出 功能。
SIGFPE (信号浮点异常)错误的算术运算,例如零分频或导致溢出的运算(不一定是浮点运算)。
SIGILL (信号非法指令)无效的功能图像,例如非法指令。这通常是由于代码中的损坏或尝试执行数据。
SIGINT (信号中断)交互式注意信号。通常由应用程序用户生成。
SIGSEGV
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Linux C++中的信号量可以使用mutex和condition_variable实现。具体实现方法如下: 1.定义一个信号量类,包含一个互斥量和一个条件变量: ```c++ #include <mutex> #include <condition_variable> class Semaphore { public: Semaphore(int count = 0) : count_(count) {} void notify() { std::unique_lock<std::mutex> lock(mutex_); ++count_; cv_.notify_one(); } void wait() { std::unique_lock<std::mutex> lock(mutex_); while(count_ == 0) { cv_.wait(lock); } --count_; } private: std::mutex mutex_; std::condition_variable cv_; int count_; }; ``` 2.在需要使用信号量的地方,创建一个Semaphore对象,调用wait()方法等待信号量,调用notify()方法释放信号量: ```c++ Semaphore sem(0); // 线程1 void thread1() { // do something sem.notify(); } // 线程2 void thread2() { sem.wait(); // do something } ``` 3.使用信号量实现生产者消费者模型: ```c++ #include <iostream> #include <thread> #include <vector> class Semaphore { public: Semaphore(int count = 0) : count_(count) {} void notify() { std::unique_lock<std::mutex> lock(mutex_); ++count_; cv_.notify_one(); } void wait() { std::unique_lock<std::mutex> lock(mutex_); while(count_ == 0) { cv_.wait(lock); } --count_; } private: std::mutex mutex_; std::condition_variable cv_; int count_; }; Semaphore sem_empty(10); // 缓冲区空闲信号量 Semaphore sem_full(0); // 缓冲区满信号量 std::vector<int> buffer; // 缓冲区 void producer() { for(int i = 0; i < 100; ++i) { sem_empty.wait(); buffer.push_back(i); sem_full.notify(); } } void consumer() { for(int i = 0; i < 100; ++i) { sem_full.wait(); int data = buffer.back(); buffer.pop_back(); sem_empty.notify(); std::cout << "consume data: " << data << std::endl; } } int main() { std::thread t1(producer); std::thread t2(consumer); t1.join(); t2.join(); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值