文章目录
Pthread多线程
图像翻转
因为代码太多了,因此只放线程函数核心代码
int n; // 水平翻转时 n为ip.Vpixels 垂直翻转时为ip.Hpixels
int rank = 1; // 当前为第1个线程
int cur_n = n / thread_count; //当前线程所需要处理的行/列数
int start = rank * cur_n; // 从哪一行/列开始处理
int end = start + cur_n; // 到哪一行/列处理完毕
// 垂直翻转(上下)
for(int col = start;col<end;col+=3){
for(int row = 0;row<ip.Vpixels/2;row++){
swap( img[row][col], img[ip.Vpixels - row -1][col] );
swap( img[row][col+1], img[ip.Vpixels - row -1][col+1] );
swap( img[row][col+2], img[ip.Vpixels - row -1][col+2] );
}
}
// 水平翻转(左右)
for(row = start;row<end;row++){
for(col = 0;col<ip.Hpixels*3/2;col+=3){
swap( img[row][col], img[row][ip.Hpixel*3 - col -3] );
swap( img[row][col+1], img[row][ip.Hpixel*3 - col -2] );
swap( img[row][col+2], img[row][ip.Hpixel*3 - col -1] );
}
}
生产者消费者
信号量
int t = 0; // 消费者减t,生产者加t
sem_t empty,full; // 信号量
pthread_mutex_t mutex; // 互斥量
int main(){
pthread_t producer;
pthread_t consumer;
// 初始化互斥量
pthread_mutex_init(&mutex,NULL);
// 初始化信号量
// 第2个参数代表几个进程共享该互斥量,0代表多线程共享
sem_init(empty,0,10); // empty信号量为10
sem_init(full,0,0); // full信号量为0
// 生产者消费者函数内循环之间的时间间隔
int producer_time = 2;
int consumer_time = 3;
// 创建线程
pthread_create(
&producer, // 指明哪个线程
NULL,
producer_function, // 线程执行什么函数
&producer_time // 传给函数的参数
);
pthread_create(
&consumer,
NULL,
consumer_function,
&consumer_time
);
// 等待线程结束
pthread_join(producer,NULL);
pthread_join(consumer,NULL);
// 销毁互斥量
pthread_mutex_destroy(&mutex);
return 0;
}
void* producer_function(void *time){
int time = *(int*) time; // 时间间隔
while(true){
sem_wait(&empty); // empty信号量减1
pthread_mutex_lock(&mutex); // 加锁
t++; // 生产
printf("生产"); // 随便写个printf意思意思
pthread_mutex_unlock(&mutex); // 解锁
sem_post(&full); //full信号量加1
sleep(time);
}
}
void* consumer_function(void *time){
int time = *(int*) time;
while(true){
sem_wait(&full);
pthread_mutex_lock(&mutex);
t--;
printf("消费");
pthread_mutex_unlock(&mutex);
sem_post(&empty);
sleep(time);
}
}
条件变量
int t = 0; // 消费者减t,生产者加t
pthread_mutex_t mutex; // 互斥量
pthread_cond_t cond_full; // 非满条件变量
pthread_cond_t cond_empty; // 非空条件变量
int main(){
pthread_t producer;
pthread_t consumer;
// 初始化互斥量
pthread_mutex_init(&mutex,NULL);
// 初始化条件变量
pthread_cond_init(&cond_full,NULL);
pthread_cond_init(&cond_empty,NULL);
// 创建线程
pthread_create(
&producer, // 指明哪个线程
NULL,
producer_function, // 线程执行什么函数
NULL // 传给函数的参数
);
pthread_create(
&consumer,
NULL,
consumer_function,
NULL
);
// 等待线程结束
pthread_join(producer,NULL);
pthread_join(consumer,NULL);
// 销毁
pthread_mutex_destroy(&mutex)