编写以简单程序实现下列功能:主进程实现每个一秒输出字母A、B、C、D…等10个字母,创建一个线程,该线程实现每秒输出数字1、2、3…等10个数字//参考例题1:thread1.c#include <stdio.h>#include <unistd.h>#include <stdlib.h>#include <string.h>#include <pthread.h>void *thread_function(void *arg);char message[] = "Hello World";void *thread_function(void *arg) {printf("thread_function is running. Argument was %s\n", (char *)arg);sleep(3);strcpy(message, "Bye!");pthread_exit("Thank you for the CPU time");}int main() {int res;pthread_t a_thread;void *thread_result;res = pthread_create(&a_thread, NULL, thread_function, (void *)message);if (res != 0) {perror("Thread creation failed");exit(EXIT_FAILURE);}printf("Waiting for thread to finish...\n");res = pthread_join(a_thread, &thread_result);if (res != 0) {perror("Thread join failed");exit(EXIT_FAILURE);}printf("Thread joined, it returned %s\n", (char *)thread_result);printf("Message is now %s\n", message);exit(EXIT_SUCCESS);}
时间: 2024-03-21 15:37:41 浏览: 119
下面是实现题目要求的简单程序:
```c
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void *print_letters(void *arg) {
int i;
for (i = 0; i < 10; i++) {
printf("%c ", 'A' + i);
fflush(stdout); // 刷新缓冲区
sleep(1);
}
pthread_exit(NULL);
}
void *print_numbers(void *arg) {
int i;
for (i = 1; i <= 10; i++) {
printf("%d ", i);
fflush(stdout); // 刷新缓冲区
sleep(1);
}
pthread_exit(NULL);
}
int main() {
pthread_t letter_thread, number_thread;
pthread_create(&letter_thread, NULL, print_letters, NULL);
pthread_create(&number_thread, NULL, print_numbers, NULL);
pthread_join(letter_thread, NULL);
pthread_join(number_thread, NULL);
return 0;
}
```
程序中使用了两个线程,一个用于输出字母,一个用于输出数字。两个线程都是通过sleep函数暂停1秒钟来实现每秒输出一个字符或数字。注意在输出字符和数字时要使用fflush(stdout)刷新缓冲区,否则可能出现输出不及时的情况。最后用pthread_join函数等待两个线程结束,释放资源。
阅读全文