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

#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 @ 2022-04-26 23:26  major825  阅读(26)  评论(0)    收藏  举报