一、题目描述:
两个线程分别打印26个英文字母的元音字母和辅音字母,分别按照字母序输出。
二、解题思路:
(1) 如果要求输出一行
感觉看代码都可以看明白了…
(2)如果要求输出两行
由于线程之间共享全局变量,所以可以将26个字母保存到一个全局数组中,并且保存当前访问到数组元素的下标。然后再创建两个数组分别保存元音字母和辅音字母,不同的线程添加不同类型的字母到对应的字母表中,最后遍历打印元音字母表和辅音字母表即可。
代码:
///////////////////////////////////////////////////////
// @title 按字母序同时输出元音字母和辅音字母(输出一行)
// @author 分时天月 on 2019/6/28
///////////////////////////////////////////////////////
#include <stdio.h>
#include <pthread.h>
char pool[27] = "abcdefghijklmnopqrstuvwxyz";
int index = 0;
void* PrintVowels(void* arg){
while(1){
if(index <= 27){
switch(pool[index]){ //如果pool中当前元素为元音字母,则添加到元音字母数组中
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
printf("%c", pool[index++]);
fflush(stdout);
break;
}
}else{
break;
}
}
return NULL;
}
void* PrintConsonants(void* arg){
while(1){
if(index <= 27){
if(pool[index] != 'a' && pool[index] != 'e'
&& pool[index] != 'i' && pool[index] != 'o' && pool[index] != 'u'){
printf("%c", pool[index++]);
fflush(stdout);
}
}else{
break;
}
}
return NULL;
}
int main() {
pthread_t tid1; //打印元音字母的线程
pthread_t tid2; //打印辅音字母的线程
pthread_create(&tid1, NULL, PrintVowels, NULL);
pthread_create(&tid2, NULL, PrintConsonants, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
printf("\n");
return 0;
}
///////////////////////////////////////////////////////
// @title 分别输出元音字母和辅音字母 (输出两行)
// @author 分时天月 on 2019/6/28
///////////////////////////////////////////////////////
#include <stdio.h>
#include <pthread.h>
char pool[27] = "abcdefghijklmnopqrstuvwxyz";
int index = 0;
int i, j;
void* PrintVowels(void* vowels){
char* array = (char*)vowels;
while(1){
if(index <= 27){
switch(pool[index]){ //如果pool中当前元素为元音字母,则添加到元音字母数组中
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
array[i++] = pool[index++];
break;
}
}else{
break;
}
}
return NULL;
}
void* PrintConsonants(void* consonants){
char* array = (char*)consonants;
while(1){
if(index <= 27){
if(pool[index] != 'a' && pool[index] != 'e'
&& pool[index] != 'i' && pool[index] != 'o' && pool[index] != 'u'){
array[j++] = pool[index++];
}
}else{
break;
}
}
return NULL;
}
int main() {
pthread_t tid1; //打印元音字母的线程
pthread_t tid2; //打印辅音字母的线程
char vowels[6]; //保存元音字母
char consonantis[22]; //保存辅音字母
pthread_create(&tid1, NULL, PrintVowels, vowels);
pthread_create(&tid2, NULL, PrintConsonants, consonantis);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
for(int m = 0; m < i; ++m){
printf("%c ", vowels[m]);
}
printf("\n");
for(int m = 0; m < j; ++m){
printf("%c ", consonantis[m]);
}
printf("\n");
return 0;
}