一、題目描述
我們提供了一個(gè)類:
class ZeroEvenOdd {
public ZeroEvenOdd(int n) { ... } // 構(gòu)造函數(shù)
public void zero(printNumber) { ... } // 僅打印出 0
public void even(printNumber) { ... } // 僅打印出 偶數(shù)
public void odd(printNumber) { ... } // 僅打印出 奇數(shù)
}
相同的一個(gè) ZeroEvenOdd 類實(shí)例將會(huì)傳遞給三個(gè)不同的線程:
線程 A 將調(diào)用 zero()埃撵,它只輸出 0 。
線程 B 將調(diào)用 even()否纬,它只輸出偶數(shù)仍秤。
線程 C 將調(diào)用 odd(),它只輸出奇數(shù)彼宠。
每個(gè)線程都有一個(gè) printNumber 方法來輸出一個(gè)整數(shù)鳄虱。請修改給出的代碼以輸出整數(shù)序列 010203040506... ,其中序列的長度必須為 2n凭峡。
示例 1:
輸入:n = 2
輸出:"0102"
說明:三條線程異步執(zhí)行拙已,其中一個(gè)調(diào)用 zero(),另一個(gè)線程調(diào)用 even()摧冀,最后一個(gè)線程調(diào)用odd()倍踪。正確的輸出為 "0102"。
示例 2:
輸入:n = 5
輸出:"0102030405"
二索昂、程序?qū)嵗?/h1>
class ZeroEvenOdd {
private:
int n;
pthread_mutex_t lockZero;
pthread_mutex_t lockOdd;
pthread_mutex_t lockEven;
public:
ZeroEvenOdd(int n) {
this->n = n;
pthread_mutex_init(&lockZero, NULL);
pthread_mutex_init(&lockOdd, NULL);
pthread_mutex_init(&lockEven, NULL);
pthread_mutex_lock(&lockOdd);
pthread_mutex_lock(&lockEven);
}
// printNumber(x) outputs "x", where x is an integer.
void zero(function<void(int)> printNumber) {
for(int i = 1;i <= this->n; ++i){
pthread_mutex_lock(&lockZero);
printNumber(0);
if(i%2){
pthread_mutex_unlock(&lockOdd);
}else{
pthread_mutex_unlock(&lockEven);
}
}
}
void even(function<void(int)> printNumber) {
for(int i = 2; i <= this->n; i += 2){
pthread_mutex_lock(&lockEven);
printNumber(i);
pthread_mutex_unlock(&lockZero);
}
}
void odd(function<void(int)> printNumber) {
for(int i = 1; i <= this->n ; i += 2){
pthread_mutex_lock(&lockOdd);
printNumber(i);
pthread_mutex_unlock(&lockZero);
}
}
};
class ZeroEvenOdd {
private:
int n;
pthread_mutex_t lockZero;
pthread_mutex_t lockOdd;
pthread_mutex_t lockEven;
public:
ZeroEvenOdd(int n) {
this->n = n;
pthread_mutex_init(&lockZero, NULL);
pthread_mutex_init(&lockOdd, NULL);
pthread_mutex_init(&lockEven, NULL);
pthread_mutex_lock(&lockOdd);
pthread_mutex_lock(&lockEven);
}
// printNumber(x) outputs "x", where x is an integer.
void zero(function<void(int)> printNumber) {
for(int i = 1;i <= this->n; ++i){
pthread_mutex_lock(&lockZero);
printNumber(0);
if(i%2){
pthread_mutex_unlock(&lockOdd);
}else{
pthread_mutex_unlock(&lockEven);
}
}
}
void even(function<void(int)> printNumber) {
for(int i = 2; i <= this->n; i += 2){
pthread_mutex_lock(&lockEven);
printNumber(i);
pthread_mutex_unlock(&lockZero);
}
}
void odd(function<void(int)> printNumber) {
for(int i = 1; i <= this->n ; i += 2){
pthread_mutex_lock(&lockOdd);
printNumber(i);
pthread_mutex_unlock(&lockZero);
}
}
};