Files
C-exp-collection/吕锦中202441429012406/task61.c

59 lines
1.3 KiB
C
Raw Normal View History

2026-05-14 09:27:48 +08:00
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include <unistd.h>
void *thread_T1(void *arg) {
for (int i = 1; i <= 5; i++) {
printf("My name is 吕锦中\n");
if (i < 5) {
int sleep_time = rand() % 5 + 1;
sleep(sleep_time);
}
}
return NULL;
}
void *thread_T2(void *arg) {
for (int i = 1; i <= 5; i++) {
printf("My student number is 2024414290124\n");
if (i < 5) {
int sleep_time = rand() % 5 + 1;
sleep(sleep_time);
}
}
return NULL;
}
void *thread_T3(void *arg) {
for (int i = 1; i <= 5; i++) {
time_t now = time(NULL);
struct tm *tm_info = localtime(&now);
char time_str[64];
strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", tm_info);
printf("Current time %s\n", time_str);
if (i < 5) {
int sleep_time = rand() % 5 + 1;
sleep(sleep_time);
}
}
return NULL;
}
int main() {
srand(time(NULL));
pthread_t t1, t2, t3;
pthread_create(&t1, NULL, thread_T1, NULL);
pthread_create(&t2, NULL, thread_T2, NULL);
pthread_create(&t3, NULL, thread_T3, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_join(t3, NULL);
printf("All threads finished.\n");
return 0;
}