在线程间通信中,常用的方式有共享内存、信号量、消息队列、管道等。
以下是使用共享内存实现线程间通信的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_SIZE 1024 // 共享内存的大小
typedef struct {
int counter;
} shared_data;
void* producer(void* arg) {
int shm_id;
shared_data* data;
// 创建共享内存
shm_id = shmget(IPC_PRIVATE, SHM_SIZE, IPC_CREAT | 0666);
if (shm_id == -1) {
perror("Failed to create shared memory");
exit(1);
}
// 映射共享内存
data = (shared_data*)shmat(shm_id, NULL, 0);
if (data == (shared_data*)-1) {
perror("Failed to attach shared memory");
exit(1);
}
// 写入数据
for (int i = 1; i <= 10; i++) {
data->counter = i;
printf("Producer: %d\n", i);
sleep(1); // 模拟生产过程
if (i == 10) {
data->counter = 0; // 生产完成后,设置计数器为0,表示结束
}
}
// 解除共享内存映射
if (shmdt((void*)data) == -1) {
perror("Failed to detach shared memory");
exit(1);
}
// 删除共享内存
if (shmctl(shm_id, IPC_RMID, NULL) == -1) {
perror("Failed to remove shared memory");
exit(1);
}
pthread_exit(NULL);
}
void* consumer(void* arg) {
int shm_id;
shared_data* data;
// 获取共享内存
shm_id = shmget(IPC_PRIVATE, SHM_SIZE, 0666);
if (shm_id == -1) {
perror("Failed to get shared memory");
exit(1);
}
// 映射共享内存
data = (shared_data*)shmat(shm_id, NULL, 0);
if (data == (shared_data*)-1) {
perror("Failed to attach shared memory");
exit(1);
}
// 读取数据
int value;
while (1) {
value = data->counter;
if (value == 0) {
break; // 计数器为0,表示生产过程结束,停止消费
}
printf("Consumer: %d\n", value);
sleep(1); // 模拟消费过程
}
// 解除共享内存映射
if (shmdt((void*)data) == -1) {
perror("Failed to detach shared memory");
exit(1);
}
pthread_exit(NULL);
}
int main() {
pthread_t producer_thread, consumer_thread;
// 创建生产者线程
if (pthread_create(&producer_thread, NULL, producer, NULL) != 0) {
perror("Failed to create producer thread");
exit(1);
}
// 创建消费者线程
if (pthread_create(&consumer_thread, NULL, consumer, NULL) != 0) {
perror("Failed to create consumer thread");
exit(1);
}
// 等待线程结束
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
return 0;
}
以上代码中,我们使用共享内存作为线程间通信的介质。生产者线程将数据写入共享内存,消费者线程从共享内存中读取数据。通过共享内存,生产者和消费者可以直接读写共享的数据,实现了线程间的通信。