线程间通信和进程间通信

线程间通信

#include <iostream>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <chrono>

// 全局变量
std::queue<int> data_queue;
std::mutex mtx;
std::condition_variable cv_data; // 当队列有数据时,通知消费者
std::condition_variable cv_stop; // 当生产者停止时,通知消费者
bool stop = false;

std::thread::id getCurrentThreadId() {
    return std::this_thread::get_id();
}

// 生产者线程
void producer() {
    for (int i = 0; i < 10; ++i) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 模拟耗时操作

        std::lock_guard<std::mutex> lock(mtx);
        data_queue.push(i);
        std::cout << "threadid:"<< getCurrentThreadId() << " Produced: " << i << std::endl;
        cv_data.notify_one(); // 通知消费者有新数据
    }

    // 通知消费者停止
    {
        std::lock_guard<std::mutex> lock(mtx);
        stop = true;
    }
    cv_stop.notify_one();
}

// 消费者线程
void consumer() {
    while (true) {
        std::unique_lock<std::mutex> lock(mtx);

        // 等待数据或停止信号
        cv_data.wait(lock, []{ return !data_queue.empty() || stop; });

        if (stop && data_queue.empty()) {
            // 收到停止信号且队列为空,则退出
            break;
        }

        int value = data_queue.front();
        data_queue.pop();

        lock.unlock(); // 解锁以允许其他线程访问队列

        std::cout<< "threadid:"<< getCurrentThreadId() << " Consumed: " << value << std::endl;

        // 模拟处理数据的时间
        std::this_thread::sleep_for(std::chrono::milliseconds(200));
    }
}

int main() {
    std::thread producer_thread(producer);
    std::thread consumer_thread(consumer);

    producer_thread.join();
    consumer_thread.join();

    std::cout << "All tasks completed." << std::endl;
    return 0;
}

进程间通信

使用POSIX命名管道(也称为FIFO)在Unix/Linux环境下实现进程间通信的简单示例

生产者

#include <iostream>
#include <fstream>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

// 封装函数,返回当前进程的PID
pid_t get_current_process_id() {
    return getpid();
}

int main() {
    const char* fifo_name = "/tmp/my_fifo";

    // 创建FIFO,如果已存在则不创建
    mkfifo(fifo_name, 0666);

    // 打开FIFO以写入数据
    int fd = open(fifo_name, O_WRONLY);
    if (fd == -1) {
        perror("open");
        return 1;
    }

    const char* data = "Hello from producer!";
    ssize_t num_bytes = write(fd, data, strlen(data) + 1); // 包含字符串结束符'\0'
    if (num_bytes == -1) {
        perror("write");
        return 1;
    }

    close(fd);

    std::cout <<"Current process ID:"<< get_current_process_id() << "  Data written to FIFO." << std::endl;

    return 0;
}

消费者

#include <iostream>
#include <fstream>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
// 封装函数,返回当前进程的PID
pid_t get_current_process_id() {
    return getpid();
}

int main() {
    const char* fifo_name = "/tmp/my_fifo";

    // 打开FIFO以读取数据
    int fd = open(fifo_name, O_RDONLY);
    if (fd == -1) {
        perror("open");
        return 1;
    }

    char buffer[256];
    ssize_t num_bytes = read(fd, buffer, sizeof(buffer) - 1); // 保留一个位置给'\0'
    if (num_bytes == -1) {
        perror("read");
        return 1;
    }
    buffer[num_bytes] = '\0'; // 添加字符串结束符

    close(fd);
    std::cout <<"Current process ID:"<< get_current_process_id()<< "  Data read from FIFO: " << buffer << std::endl;
    return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值