LeetCode 按序打印 题解

题目描述

给你一个类:

public class Foo {
  public void first() { print("first"); }
  public void second() { print("second"); }
  public void third() { print("third"); }
}
三个不同的线程 A、B、C 将会共用一个 Foo 实例。

线程 A 将会调用 first() 方法
线程 B 将会调用 second() 方法
线程 C 将会调用 third() 方法
请设计修改程序,以确保 second() 方法在 first() 方法之后被执行,third() 方法在 second() 方法之后被执行。

思路:用互斥锁或者信息量等方法都可以实现。

题解:

方法一(信息量的方法):主要就是信息量的释放sem_post和等待函数sem_wait的使用

typedef struct {
    // User defined data may be declared here.
    sem_t t1,t2;
    
} Foo;

Foo* fooCreate() {
    Foo* obj = (Foo*) malloc(sizeof(Foo));
    sem_init(&obj->t1,0,0);
    sem_init(&obj->t2,0,0);
    // Initialize user defined data here.
    
    return obj;
}

void first(Foo* obj) {
    
    // printFirst() outputs "first". Do not change or remove this line.
    printFirst();
    sem_post(&obj->t1);
}

void second(Foo* obj) {
    sem_wait(&obj->t1);
    // printSecond() outputs "second". Do not change or remove this line.
    printSecond();
    sem_post(&obj->t2);
}

void third(Foo* obj) {
    sem_wait(&obj->t2);
    // printThird() outputs "third". Do not change or remove this line.
    printThird();
}

void fooFree(Foo* obj) {
    // User defined data may be cleaned up here.
    free(obj);
}

方法二(互斥锁法):主要是开锁关锁的问题,实际上和信息量法差不多;

typedef struct {
    // User defined data may be declared here.
    pthread_mutex_t t1,t2;
    
} Foo;

Foo* fooCreate() {
    Foo* obj = (Foo*) malloc(sizeof(Foo));
    
    // Initialize user defined data here.
    pthread_mutex_init(&obj->t1,NULL);
    pthread_mutex_init(&obj->t2,NULL);
    pthread_mutex_lock(&obj->t1);
    pthread_mutex_lock(&obj->t2);
    return obj;
}

void first(Foo* obj) {
    
    // printFirst() outputs "first". Do not change or remove this line.
    printFirst();
    pthread_mutex_unlock(&obj->t1);
}

void second(Foo* obj) {
    pthread_mutex_lock(&obj->t1);
    // printSecond() outputs "second". Do not change or remove this line.
    printSecond();
    pthread_mutex_unlock(&obj->t2);
}

void third(Foo* obj) {
    pthread_mutex_lock(&obj->t2);
    pthread_mutex_unlock(&obj->t1);
    // printThird() outputs "third". Do not change or remove this line.
    printThird();
    pthread_mutex_lock(&obj->t1);
}

void fooFree(Foo* obj) {
    // User defined data may be cleaned up here.
    pthread_mutex_destroy(&obj->t1);
    pthread_mutex_destroy(&obj->t2);
    free(obj);
    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值