当然,下面是对每行代码的解释:
c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
加载所需的头文件,包括标准输入输出库、标准库和线程库。
c
#define BUFFER_SIZE 10
定义缓冲区的大小为10。
c
typedef struct {
int buffer[BUFFER_SIZE];
int index;
pthread_mutex_t mutex;
} SharedData;
定义一个结构体SharedData,包含一个整型数组buffer作为缓冲区,一个整型变量index表示缓冲区的下标,以及一个互斥锁mutex用于保护共享数据的访问。
c
void* producer(void* arg) {
SharedData* data = (SharedData*) arg;
for (int i = 0; i < BUFFER_SIZE; ++i) {
pthread_mutex_lock(&data->mutex);
data->buffer[i] = i;
data->index++;
pthread_mutex_unlock(&data->mutex);
}
pthread_exit(NULL);
}
定义生产者线程的执行函数producer,接收一个SharedData结构体作为参数。在循环中,使用互斥锁锁定共享数据,将数据写入缓冲区,并更新缓冲区的下标。最后释放互斥锁。
c
void* consumer(void* arg) {
SharedData* data = (SharedData*) arg;
for (int i = 0; i < BUFFER_SIZE; ++i) {
pthread_mutex_lock(&data->mutex);
int value = data->buffer[i];
pthread_mutex_unlock(&data->mutex);
printf("Consumer read: %d\n", value);
}
pthread_exit(NULL);
}
定义消费者线程的执行函数consumer,同样接收一个SharedData结构体作为参数。在循环中,使用互斥锁锁定共享数据,读取缓冲区中的数据,并打印出来。最后释放互斥锁。
c
int main() {
pthread_t producerThread, consumerThread;
SharedData data;
data.index = 0;
pthread_mutex_init(&data.mutex, NULL);
pthread_create(&producerThread, NULL, producer, &data);
pthread_create(&consumerThread, NULL, consumer, &data);
pthread_join(producerThread, NULL);
pthread_join(consumerThread, NULL);
pthread_mutex_destroy(&data.mutex);
return 0;
}
程序的主函数,定义了两个线程的pthread_t对象producerThread和consumerThread。创建一个SharedData结构体对象data,并初始化其下标和互斥锁。然后,使用pthread_create函数创建生产者线程和消费者线程,并传递data对象作为参数。接着使用pthread_join函数等待线程的结束。最后,使用pthread_mutex_destroy销毁互斥锁,并返回0。
以上就是每行代码的简要解释。希望能对你有所帮助!