1、 定义一个全局数组int a[10];实现一个线程循环正序打印,一个线程循环逆序打印,要求先正序再逆序

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>

int a[10] = {1,2,3,4,5,6,7,8,9,10};
sem_t sem1, sem2;

void *thread_func1(void *arg)
{
    int i;
    while (1)
    {
        sem_wait(&sem1);
        for (i = 0; i < 10; i++)
            printf("%d ", a[i]);
        printf("\n");
        sem_post(&sem2);
        //sleep(1);
    }
}

void *thread_func2(void *arg)
{
    int i;
    while (1)
    {
        sem_wait(&sem2);
        for (i = 9; i >= 0; i--)
            printf("%d ", a[i]);
        printf("\n");
        sem_post(&sem1);
        //sleep(1);
    }
    
}

int main(int argc, char *argv[])
{ 
    pthread_t thread1, thread2;
    int err;
    sem_init(&sem1, 0, 1); //生产者信号量:1
    sem_init(&sem2, 0, 0); //消费者信号量:0

    err = pthread_create(&thread1, NULL, thread_func1, NULL);
    if (err != 0)
    {
        fprintf(stderr, "pthread_create1: %s\n", strerror(err));
        return -1;
    }
    
    err = pthread_create(&thread2, NULL, thread_func2, NULL);
    if (err != 0)
    {
        fprintf(stderr, "pthread_create2: %s\n", strerror(err));
        return -1;
    }
    while (1)
        sleep(1);

    return 0;
} 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值