在一个子线程中打印出数组,在另一个子线程中将数组逆序

#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>
#include <string.h>
#include <stdlib.h>
int buf[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
// sem_t input_sem;//定义2个信号量,读和写信号量
// sem_t output_sem;

pthread_mutex_t mlock = PTHREAD_MUTEX_INITIALIZER;

void *input_thread(void *arg)
{
while(1){
// sem_wait(&input_sem);
pthread_mutex_lock(&mlock);
int i = 0;
for(i = 0; i < sizeof(buf)/sizeof(int); i++){
printf("%d ", buf[i]);
}
printf("\n");
// sem_post(&output_sem);
pthread_mutex_unlock(&mlock);
}
}

void *output_thread(void *arg)
{
while(1){
// sem_wait(&output_sem);
pthread_mutex_lock(&mlock);
int i = 0,temp;
int n = sizeof(buf)/sizeof(int);
int len = n/2;
for(i = 0; i< len; i++){
temp = buf[i];
buf[i] = buf[n - 1- i];
buf[n-1-i] = temp;
}
// sem_post(&input_sem);
pthread_mutex_unlock(&mlock);

}
}
int main(int argc, const char *argv[])
{
// sem_init(&input_sem,0,1);//初始化信号量,写信号量获得初值1,申请写资源可执行程序
// sem_init(&output_sem,0,0);

int ret1;
int ret2;
pthread_t tid1;
pthread_t tid2;
ret1 = pthread_create(&tid1, NULL, input_thread, NULL);
ret2 = pthread_create(&tid2, NULL, output_thread, NULL);

pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}

posted @   major825  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示