线程间通信
#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_t get_current_process_id() {
return getpid();
}
int main() {
const char* fifo_name = "/tmp/my_fifo";
mkfifo(fifo_name, 0666);
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);
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_t get_current_process_id() {
return getpid();
}
int main() {
const char* fifo_name = "/tmp/my_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);
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;
}