任务 1:编写程序 task31.c,主线程创建 3 个对等线程 T1、T2、T3,每个线程利用循环执行 5 次
printf 输出操作,两次循环间随机等待 1-5s 时间。主线程等待所有对等线程结束后终止进程。各对等
线程的输出操作是:
T1:输出“My name is <您的姓名 xxx>”
T2:输出“My student number is <您的学号 xxx>”
T3:输出“Current time <当前时间,包括年月日时分秒>
task31.c
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<unistd.h>
#include<pthread.h>
void* thread_name(){
for(int i=0;i<5;i++){
printf("My name is \n");
int time = rand()%5+1;
sleep(time);
}
}
void* thread_num(){
for(int i=0;i<5;i++){
printf("My student number is\n");
int time = rand()%5+1;
sleep(time);
}
}
void* thread_time(){
time_t now;
for(int i=0;i<5;i++){
struct tm *tm_now;
time(&now);
tm_now = localtime(&now);
printf("Current time is: %d-%d-%d %d:%d:%d\n",
tm_now->tm_year+1900, tm_now->tm_mon+1, tm_now->tm_mday, tm_now->tm_hour, tm_now->tm_min, tm_now->tm_sec);
int time = rand()%5+1;
sleep(time);
}
}
int main(){
pthread_t t1,t2,t3;
pthread_create(&t1,NULL,thread_name,NULL);
pthread_create(&t2,NULL,thread_num,NULL);
pthread_create(&t3,NULL,thread_time,NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_join(t3,