写一个c语言程序要求创建两个线程一个用来更改颜色一个用来用户输入
这是一个简单的C语言程序,其中创建了两个线程,一个用来更改颜色,一个用来用户输入。更改颜色的线程会不断地循环,每隔一段时间就会更改一次颜色。用户输入的线程会等待用户输入,然后将输入的内容输出到屏幕上。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
void *change_color(void *arg) {
while (1) {
printf("\033[0;31m"); // 设置字体颜色为红色
sleep(1); // 等待1秒
printf("\033[0m"); // 恢复字体颜色
sleep(1); // 等待1秒
}
return NULL;
}
void *user_input(void *arg) {
char input[256];
while (1) {
printf("请输入内容:");
fgets(input, 256, stdin); // 读取用户输入
printf("你输入的是:%s", input);
}
return NULL;
}
int main() {
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, change_color, NULL);
pthread_create(&tid2, NULL, user_input, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
return 0;
}
在该程序中,使用了ANSI转义序列来改变字体颜色。使用"\033[0;31m"可以将字体颜色设置为红色,"\033[0m"可以将字体颜色恢复为默认颜色。fgets函数用来读取用户输入,它会读取用户输入的一行文本,保存到input数组中。线程的创建和销毁使用了pthread库提供的函数pthread_create和pthread_join。
原文地址: https://www.cveoy.top/t/topic/8l9 著作权归作者所有。请勿转载和采集!