第9讲:多核编程基础
多核处理器架构
多核处理器概述
多核处理器是指在一个物理芯片上集成多个处理核心的处理器,每个核心都可以独立执行指令。 多核处理器的优势- 性能提升:多个核心可以并行执行任务
- 能效优化:相比提高单核频率,多核更节能
- 并行处理:支持真正的并行计算
- 负载均衡:任务可以分配到不同核心
多核处理器架构类型
对称多处理(SMP)┌─────────────────────────────────────┐
│ 共享内存 │
├─────────────┬─────────────┬──────────┤
│ Core 1 │ Core 2 │ Core 3 │
│ │ │ │
│ L1 Cache │ L1 Cache │ L1 Cache │
│ L2 Cache │ L2 Cache │ L2 Cache │
└─────────────┴─────────────┴──────────┘
共享总线
┌─────────────────┐ ┌─────────────────┐
│ Node 1 │ │ Node 2 │
├───────────────┤ ├───────────────┤
│ Core 1 │ │ Core 3 │
│ Core 2 │ │ Core 4 │
│ Local Mem │ │ Local Mem │
└───────────────┘ └───────────────┘
│ │
└─────────┬──────────┘
│
Interconnect
│
System Memory
缓存一致性协议
MESI协议- Modified:数据被修改,仅在本缓存中有效
- Exclusive:数据未修改,仅在本缓存中有效
- Shared:数据未修改,可能在多个缓存中存在
- Invalid:缓存行无效
// MESI状态转换示例
typedef enum {
MESI_MODIFIED,
MESI_EXCLUSIVE,
MESI_SHARED,
MESI_INVALID
} mesi_state_t;
typedef struct {
mesi_state_t state; // MESI状态
uint64_t tag; // 缓存标签
int dirty; // 是否脏数据
char data[CACHE_LINE_SIZE]; // 缓存数据
} cache_line_t;
// MESI状态转换
void mesi_state_transition(cache_line_t *line, mesi_event_t event) {
switch (line->state) {
case MESI_INVALID:
if (event == MESI_READ) {
line->state = MESI_SHARED;
line->dirty = 0;
}
break;
case MESI_SHARED:
if (event == MESI_WRITE) {
// 发送失效请求给其他核心
send_invalidate_request(line);
line->state = MESI_MODIFIED;
line->dirty = 1;
}
break;
case MESI_EXCLUSIVE:
if (event == MESI_WRITE) {
line->state = MESI_MODIFIED;
line->dirty = 1;
} else if (event == MESI_READ_SHARING) {
line->state = MESI_SHARED;
}
break;
case MESI_MODIFIED:
if (event == MESI_READ_SHARING) {
// 写回数据到主存
write_back_to_memory(line);
line->state = MESI_SHARED;
line->dirty = 0;
}
break;
}
}
内存屏障
// 内存屏障类型
#define MEMORY_BARRIER() __asm__ __volatile__("" ::: "memory")
#define READ_BARRIER() __asm__ __volatile__("" ::: "memory")
#define WRITE_BARRIER() __asm__ __volatile__("" ::: "memory")
#define FULL_BARRIER() __asm__ __volatile__("mfence" ::: "memory")
// 内存屏障的使用示例
void memory_barrier_example(void) {
int data = 42;
int flag = 0;
// 确保写入顺序
data = 100; // 写入数据
WRITE_BARRIER(); // 写屏障
flag = 1; // 写入标志
// 确保读取顺序
if (flag) { // 读取标志
READ_BARRIER(); // 读屏障
printf("data = %d\n", data); // 读取数据
}
}
并行编程模型
共享内存模型
线程共享内存#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int counter;
pthread_mutex_t mutex;
} shared_data_t;
// 线程函数
void* thread_function(void *arg) {
shared_data_t *data = (shared_data_t *)arg;
for (int i = 0; i < 1000000; i++) {
pthread_mutex_lock(&data->mutex);
data->counter++;
pthread_mutex_unlock(&data->mutex);
}
return NULL;
}
int main() {
pthread_t thread1, thread2;
shared_data_t data;
// 初始化共享数据
data.counter = 0;
pthread_mutex_init(&data.mutex, NULL);
// 创建线程
pthread_create(&thread1, NULL, thread_function, &data);
pthread_create(&thread2, NULL, thread_function, &data);
// 等待线程结束
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("Final counter: %d\n", data.counter);
// 清理资源
pthread_mutex_destroy(&data.mutex);
return 0;
}
消息传递模型
基于消息的通信#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
// 消息结构
typedef struct {
long mtype; // 消息类型
char mtext[256]; // 消息内容
} message_t;
// 发送者
void sender(int msgid) {
message_t msg;
msg.mtype = 1;
for (int i = 0; i < 10; i++) {
sprintf(msg.mtext, "Message %d", i);
if (msgsnd(msgid, &msg, strlen(msg.mtext) + 1, 0) == -1) {
perror("msgsnd");
exit(1);
}
printf("Sent: %s\n", msg.mtext);
sleep(1);
}
// 发送结束消息
msg.mtype = 2;
strcpy(msg.mtext, "END");
msgsnd(msgid, &msg, strlen(msg.mtext) + 1, 0);
}
// 接收者
void receiver(int msgid) {
message_t msg;
int end_received = 0;
while (!end_received) {
if (msgrcv(msgid, &msg, sizeof(msg.mtext), 0, 0) == -1) {
perror("msgrcv");
exit(1);
}
if (msg.mtype == 1) {
printf("Received: %s\n", msg.mtext);
} else if (msg.mtype == 2) {
end_received = 1;
}
}
}
int main() {
key_t key;
int msgid;
// 创建消息队列
key = ftok("/tmp", 'A');
msgid = msgget(key, 0666 | IPC_CREAT);
if (msgid == -1) {
perror("msgget");
exit(1);
}
// 创建子进程
pid_t pid = fork();
if (pid == 0) {
// 子进程 - 接收者
receiver(msgid);
exit(0);
} else if (pid > 0) {
// 父进程 - 发送者
sender(msgid);
// 等待子进程结束
wait(NULL);
// 删除消息队列
msgctl(msgid, IPC_RMID, NULL);
} else {
perror("fork");
exit(1);
}
return 0;
}
数据并行模型
OpenMP并行编程#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
// 数组求和
int parallel_sum(int *array, int size) {
int sum = 0;
#pragma omp parallel for reduction(+:sum)
for (int i = 0; i < size; i++) {
sum += array[i];
}
return sum;
}
// 矩阵乘法
void matrix_multiply(double *A, double *B, double *C, int n) {
#pragma omp parallel for collapse(2)
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
double sum = 0.0;
for (int k = 0; k < n; k++) {
sum += A[i * n + k] * B[k * n + j];
}
C[i * n + j] = sum;
}
}
}
int main() {
const int size = 1000000;
int *array = malloc(size * sizeof(int));
// 初始化数组
#pragma omp parallel for
for (int i = 0; i < size; i++) {
array[i] = i + 1;
}
// 并行求和
int sum = parallel_sum(array, size);
printf("Sum: %d\n", sum);
free(array);
return 0;
}
任务并行模型
Intel TBB任务并行#include <iostream>
#include <vector>
#include <tbb/parallel_for.h>
#include <tbb/blocked_range.h>
#include <tbb/task_scheduler_init.h>
class MatrixMultiply {
const double* A;
const double* B;
double* C;
int size;
public:
MatrixMultiply(const double* A, const double* B, double* C, int size)
: A(A), B(B), C(C), size(size) {}
void operator()(const tbb::blocked_range2d<size_t>& r) const {
for (size_t i = r.rows().begin(); i != r.rows().end(); ++i) {
for (size_t j = r.cols().begin(); j != r.cols().end(); ++j) {
double sum = 0.0;
for (size_t k = 0; k < size; ++k) {
sum += A[i * size + k] * B[k * size + j];
}
C[i * size + j] = sum;
}
}
}
};
int main() {
const int size = 1000;
std::vector<double> A(size * size);
std::vector<double> B(size * size);
std::vector<double> C(size * size);
// 初始化矩阵
tbb::parallel_for(0, size, [&](int i) {
for (int j = 0; j < size; j++) {
A[i * size + j] = i + j;
B[i * size + j] = i - j;
}
});
// 并行矩阵乘法
tbb::parallel_for(tbb::blocked_range2d<size_t>(0, size, 0, size),
MatrixMultiply(A.data(), B.data(), C.data(), size));
std::cout << "Matrix multiplication completed" << std::endl;
return 0;
}
线程的概念与实现
线程的基本概念
线程是进程中的执行单元,是CPU调度的基本单位。同一进程中的线程共享进程的地址空间和资源。 线程的特点- 轻量级:创建和切换开销比进程小
- 共享内存:同一进程的线程共享内存空间
- 独立执行:每个线程有独立的执行流
- 并发执行:多个线程可以并发执行
POSIX线程(pthread)
线程创建和管理#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
// 线程参数结构
typedef struct {
int thread_id;
char *message;
} thread_data_t;
// 线程函数
void* thread_function(void *arg) {
thread_data_t *data = (thread_data_t *)arg;
printf("Thread %d: %s\n", data->thread_id, data->message);
// 模拟工作
for (int i = 0; i < 5; i++) {
printf("Thread %d working... %d\n", data->thread_id, i);
sleep(1);
}
printf("Thread %d finished\n", data->thread_id);
return NULL;
}
int main() {
pthread_t threads[3];
thread_data_t thread_data[3];
// 创建线程
for (int i = 0; i < 3; i++) {
thread_data[i].thread_id = i;
thread_data[i].message = "Hello from thread";
int result = pthread_create(&threads[i], NULL,
thread_function, &thread_data[i]);
if (result != 0) {
fprintf(stderr, "Error creating thread %d\n", i);
exit(1);
}
}
// 等待所有线程完成
for (int i = 0; i < 3; i++) {
pthread_join(threads[i], NULL);
}
printf("All threads completed\n");
return 0;
}
#include <pthread.h>
#include <stdio.h>
void* thread_function(void *arg) {
printf("Thread running\n");
return NULL;
}
int main() {
pthread_t thread;
pthread_attr_t attr;
// 初始化线程属性
pthread_attr_init(&attr);
// 设置分离状态
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
// 设置调度策略
pthread_attr_setschedpolicy(&attr, SCHED_RR);
// 设置调度参数
struct sched_param param;
param.sched_priority = 10;
pthread_attr_setschedparam(&attr, ¶m);
// 设置栈大小
size_t stack_size = 1024 * 1024; // 1MB
pthread_attr_setstacksize(&attr, stack_size);
// 创建线程
pthread_create(&thread, &attr, thread_function, NULL);
// 等待线程结束
pthread_join(thread, NULL);
// 销毁线程属性
pthread_attr_destroy(&attr);
return 0;
}
线程同步
互斥锁#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int value;
pthread_mutex_t mutex;
} counter_t;
// 线程函数
void* increment_counter(void *arg) {
counter_t *counter = (counter_t *)arg;
for (int i = 0; i < 1000000; i++) {
pthread_mutex_lock(&counter->mutex);
counter->value++;
pthread_mutex_unlock(&counter->mutex);
}
return NULL;
}
int main() {
pthread_t thread1, thread2;
counter_t counter;
// 初始化计数器
counter.value = 0;
pthread_mutex_init(&counter.mutex, NULL);
// 创建线程
pthread_create(&thread1, NULL, increment_counter, &counter);
pthread_create(&thread2, NULL, increment_counter, &counter);
// 等待线程结束
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("Final counter value: %d\n", counter.value);
// 清理资源
pthread_mutex_destroy(&counter.mutex);
return 0;
}
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
typedef struct {
int buffer[10];
int count;
pthread_mutex_t mutex;
pthread_cond_t not_empty;
pthread_cond_t not_full;
} buffer_t;
// 生产者
void* producer(void *arg) {
buffer_t *buffer = (buffer_t *)arg;
int item = 0;
while (1) {
pthread_mutex_lock(&buffer->mutex);
// 等待缓冲区不满
while (buffer->count >= 10) {
pthread_cond_wait(&buffer->not_full, &buffer->mutex);
}
// 生产项目
buffer->buffer[buffer->count] = item++;
buffer->count++;
printf("Produced item %d, buffer size: %d\n",
item - 1, buffer->count);
// 通知消费者
pthread_cond_signal(&buffer->not_empty);
pthread_mutex_unlock(&buffer->mutex);
sleep(1);
}
return NULL;
}
// 消费者
void* consumer(void *arg) {
buffer_t *buffer = (buffer_t *)arg;
while (1) {
pthread_mutex_lock(&buffer->mutex);
// 等待缓冲区不空
while (buffer->count <= 0) {
pthread_cond_wait(&buffer->not_empty, &buffer->mutex);
}
// 消费项目
int item = buffer->buffer[--buffer->count];
printf("Consumed item %d, buffer size: %d\n",
item, buffer->count);
// 通知生产者
pthread_cond_signal(&buffer->not_full);
pthread_mutex_unlock(&buffer->mutex);
sleep(2);
}
return NULL;
}
int main() {
pthread_t producer_thread, consumer_thread;
buffer_t buffer;
// 初始化缓冲区
buffer.count = 0;
pthread_mutex_init(&buffer.mutex, NULL);
pthread_cond_init(&buffer.not_empty, NULL);
pthread_cond_init(&buffer.not_full, NULL);
// 创建线程
pthread_create(&producer_thread, NULL, producer, &buffer);
pthread_create(&consumer_thread, NULL, consumer, &buffer);
// 等待线程结束(实际中可能需要信号处理)
sleep(30);
return 0;
}
线程池
线程池实现#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>
#define MAX_THREADS 10
#define MAX_QUEUE 100
typedef struct {
void (*function)(void*);
void *argument;
} task_t;
typedef struct {
task_t *tasks[MAX_QUEUE];
int queue_size;
int queue_front;
int queue_rear;
pthread_mutex_t lock;
pthread_cond_t not_empty;
pthread_cond_t not_full;
bool shutdown;
} thread_pool_t;
typedef struct {
thread_pool_t *pool;
pthread_t thread;
} thread_worker_t;
// 线程工作函数
void* thread_worker(void *arg) {
thread_worker_t *worker = (thread_worker_t *)arg;
thread_pool_t *pool = worker->pool;
while (1) {
pthread_mutex_lock(&pool->lock);
// 等待任务
while (pool->queue_size == 0 && !pool->shutdown) {
pthread_cond_wait(&pool->not_empty, &pool->lock);
}
// 检查是否关闭
if (pool->shutdown) {
pthread_mutex_unlock(&pool->lock);
break;
}
// 获取任务
task_t *task = pool->tasks[pool->queue_front];
pool->queue_front = (pool->queue_front + 1) % MAX_QUEUE;
pool->queue_size--;
// 通知生产者
pthread_cond_signal(&pool->not_full);
pthread_mutex_unlock(&pool->lock);
// 执行任务
task->function(task->argument);
}
free(worker);
return NULL;
}
// 创建线程池
thread_pool_t* thread_pool_create(int thread_count) {
thread_pool_t *pool = malloc(sizeof(thread_pool_t));
if (!pool) return NULL;
pool->queue_size = 0;
pool->queue_front = 0;
pool->queue_rear = 0;
pool->shutdown = false;
pthread_mutex_init(&pool->lock, NULL);
pthread_cond_init(&pool->not_empty, NULL);
pthread_cond_init(&pool->not_full, NULL);
// 创建工作线程
for (int i = 0; i < thread_count; i++) {
thread_worker_t *worker = malloc(sizeof(thread_worker_t));
worker->pool = pool;
if (pthread_create(&worker->thread, NULL, thread_worker, worker) != 0) {
free(worker);
continue;
}
}
return pool;
}
// 添加任务到线程池
int thread_pool_add_task(thread_pool_t *pool, void (*function)(void*), void *argument) {
pthread_mutex_lock(&pool->lock);
// 等待队列不满
while (pool->queue_size >= MAX_QUEUE && !pool->shutdown) {
pthread_cond_wait(&pool->not_full, &pool->lock);
}
if (pool->shutdown) {
pthread_mutex_unlock(&pool->lock);
return -1;
}
// 添加任务
task_t *task = malloc(sizeof(task_t));
task->function = function;
task->argument = argument;
pool->tasks[pool->queue_rear] = task;
pool->queue_rear = (pool->queue_rear + 1) % MAX_QUEUE;
pool->queue_size++;
// 通知消费者
pthread_cond_signal(&pool->not_empty);
pthread_mutex_unlock(&pool->lock);
return 0;
}
// 销毁线程池
void thread_pool_destroy(thread_pool_t *pool) {
pthread_mutex_lock(&pool->lock);
pool->shutdown = true;
pthread_mutex_unlock(&pool->lock);
// 唤醒所有线程
pthread_cond_broadcast(&pool->not_empty);
pthread_cond_broadcast(&pool->not_full);
// 等待所有线程结束(简化实现)
sleep(1);
// 清理资源
pthread_mutex_destroy(&pool->lock);
pthread_cond_destroy(&pool->not_empty);
pthread_cond_destroy(&pool->not_full);
free(pool);
}
// 示例任务函数
void example_task(void *arg) {
int task_id = *(int *)arg;
printf("Task %d executed by thread %lu\n",
task_id, (unsigned long)pthread_self());
sleep(1);
free(arg);
}
int main() {
// 创建线程池
thread_pool_t *pool = thread_pool_create(5);
// 添加任务
for (int i = 0; i < 20; i++) {
int *task_id = malloc(sizeof(int));
*task_id = i;
thread_pool_add_task(pool, example_task, task_id);
}
// 等待任务完成
sleep(5);
// 销毁线程池
thread_pool_destroy(pool);
return 0;
}
线程本地存储
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
// 线程本地存储键
pthread_key_t thread_key;
// 线程本地数据清理函数
void thread_data_cleanup(void *data) {
printf("Cleaning up thread data: %s\n", (char *)data);
free(data);
}
// 线程函数
void* thread_function(void *arg) {
int thread_id = *(int *)arg;
// 设置线程本地数据
char *data = malloc(100);
sprintf(data, "Thread %d data", thread_id);
pthread_setspecific(thread_key, data);
// 获取线程本地数据
char *local_data = (char *)pthread_getspecific(thread_key);
printf("Thread %d: %s\n", thread_id, local_data);
return NULL;
}
int main() {
pthread_t threads[3];
int thread_ids[3];
// 创建线程本地存储键
pthread_key_create(&thread_key, thread_data_cleanup);
// 创建线程
for (int i = 0; i < 3; i++) {
thread_ids[i] = i;
pthread_create(&threads[i], NULL, thread_function, &thread_ids[i]);
}
// 等待线程结束
for (int i = 0; i < 3; i++) {
pthread_join(threads[i], NULL);
}
// 删除线程本地存储键
pthread_key_delete(thread_key);
return 0;
}
多核编程最佳实践
性能优化技巧
1. 减少锁竞争// 使用细粒度锁
typedef struct {
int data[100];
pthread_mutex_t locks[10]; // 每10个元素一个锁
} fine_grained_data_t;
void update_element(fine_grained_data_t *data, int index, int value) {
int lock_index = index / 10;
pthread_mutex_lock(&data->locks[lock_index]);
data->data[index] = value;
pthread_mutex_unlock(&data->locks[lock_index]);
}
#include <stdatomic.h>
typedef struct {
atomic_int value;
} atomic_counter_t;
void atomic_increment(atomic_counter_t *counter) {
atomic_fetch_add(&counter->value, 1);
}
int atomic_get(atomic_counter_t *counter) {
return atomic_load(&counter->value);
}
// 批量处理减少锁竞争
typedef struct {
int buffer[100];
int count;
pthread_mutex_t mutex;
} batch_buffer_t;
void batch_add(batch_buffer_t *buffer, int value) {
pthread_mutex_lock(&buffer->mutex);
buffer->buffer[buffer->count++] = value;
// 批量处理
if (buffer->count >= 100) {
process_batch(buffer->buffer, buffer->count);
buffer->count = 0;
}
pthread_mutex_unlock(&buffer->mutex);
}
调试多核程序
1. 竞态条件检测#include <pthread.h>
#include <stdio.h>
int shared_counter = 0;
pthread_mutex_t debug_mutex;
void debug_log(const char *message) {
pthread_mutex_lock(&debug_mutex);
printf("[%lu] %s\n", (unsigned long)pthread_self(), message);
pthread_mutex_unlock(&debug_mutex);
}
void* thread_function(void *arg) {
for (int i = 0; i < 1000; i++) {
debug_log("About to increment counter");
shared_counter++;
debug_log("Incremented counter");
}
return NULL;
}
#include <time.h>
#include <stdio.h>
typedef struct {
struct timespec start;
struct timespec end;
} timer_t;
void timer_start(timer_t *timer) {
clock_gettime(CLOCK_MONOTONIC, &timer->start);
}
void timer_stop(timer_t *timer) {
clock_gettime(CLOCK_MONOTONIC, &timer->end);
}
double timer_elapsed(timer_t *timer) {
double start_sec = timer->start.tv_sec + timer->start.tv_nsec / 1e9;
double end_sec = timer->end.tv_sec + timer->end.tv_nsec / 1e9;
return end_sec - start_sec;
}
课后练习
- 思考题:分析多核处理器中缓存一致性协议的重要性,讨论MESI协议的优缺点。
- 编程题:实现一个生产者-消费者模型,使用多个生产者和消费者线程。
- 设计题:设计一个适合AI训练的多线程数据加载器,考虑并行预处理和内存管理。
下一讲预告
第10讲:同步与互斥 - 临界区问题、互斥锁的实现、信号量机制。B站视频:南京大学操作系统2025 - 第9讲 课程讲义:jyywiki.cn/OS/2025/lect9.md