实现思路
- 使用互斥锁(Mutex):在分配内存和使用内存的操作前后分别加锁和解锁。互斥锁能保证同一时间只有一个线程可以访问共享资源,从而避免内存访问冲突。
- 条件变量(Condition Variable):如果负责使用内存的线程需要等待内存分配完成后才能使用,可以使用条件变量。分配内存的线程在完成内存分配后通知等待在条件变量上的线程。
关键代码片段
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
// 定义互斥锁和条件变量
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
// 共享内存指针
int *shared_memory;
// 标记内存是否已分配
int memory_allocated = 0;
// 分配内存的线程函数
void *allocate_memory(void *arg) {
pthread_mutex_lock(&mutex);
shared_memory = (int *)malloc(sizeof(int));
if (shared_memory != NULL) {
*shared_memory = 42; // 初始化内存
memory_allocated = 1;
}
pthread_cond_signal(&cond); // 通知等待的线程
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
// 使用内存的线程函数
void *use_memory(void *arg) {
pthread_mutex_lock(&mutex);
while (!memory_allocated) {
pthread_cond_wait(&cond, &mutex); // 等待内存分配完成
}
if (shared_memory != NULL) {
printf("使用共享内存的值: %d\n", *shared_memory);
free(shared_memory);
}
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main() {
pthread_t tid1, tid2;
// 创建分配内存的线程
if (pthread_create(&tid1, NULL, allocate_memory, NULL)) {
printf("\n ERROR creating thread 1");
return 1;
}
// 创建使用内存的线程
if (pthread_create(&tid2, NULL, use_memory, NULL)) {
printf("\n ERROR creating thread 2");
return 1;
}
// 等待线程结束
if (pthread_join(tid1, NULL)) {
printf("\n ERROR joining thread");
return 2;
}
if (pthread_join(tid2, NULL)) {
printf("\n ERROR joining thread");
return 2;
}
// 销毁互斥锁和条件变量
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}