1、标准IO函数的时候讲解的时钟代码,要求输入quit字符串后,结束进程
程序代码
#include<stdio.h>
#include<time.h>
#include<pthread.h>
#include<string.h>
#include<unistd.h>
void *callBack(void *arg)
{
time_t t1=time(NULL);
struct tm *Time=NULL;
while(1)
{
time(&t1);
Time=localtime(&t1);
fprintf(stdout,"%4d-%02d-%02d %02d:%02d:%02d\n",\
Time->tm_year+1900,Time->tm_mon+1,Time->tm_mday,\
Time->tm_hour,Time->tm_min,Time->tm_sec);
sleep(1);
}
}
int main(int argc, const char *argv[])
{
//定义一个pthread_t类型的数,存储返回的tid号
pthread_t ttid;
//创建一个子线程
if(pthread_create(&ttid,NULL,callBack,NULL)!=0)
{
fprintf(stderr,"pthread_creat failed __%d__",__LINE__);
return -1;
}
char str[10];
pthread_detach(ttid);
A: fscanf(stdin,"%s",str);
if(strcmp("exit",str)!=0)
{
printf("请重新输入");
goto A;
}
else
return 0;
}
运行结果
ubuntu@ubuntu:作业$ gcc f_clock.c -pthread
ubuntu@ubuntu:作业$ ./a.out
2023-02-28 20:57:55
2023-02-28 20:57:56
2023-02-28 20:57:57
2023-02-28 20:57:58
2023-02-28 20:57:59
ex2023-02-28 20:58:00
i2023-02-28 20:58:01
t
ubuntu@ubuntu:作业$ ./a.out
2023-02-28 21:10:09
2023-02-28 21:10:10
aed2023-02-28 21:10:11
s
请重新输入2023-02-28 21:10:12
ex2023-02-28 21:10:13
it2023-02-28 21:10:14
2.要求定义一个全局变量char buf="1234567",创建两个线程,不考虑退出条件。
a.A线程循环打印buf字符串,
b.B线程循环倒置buf字符串,即buf种本来存储1234567,倒置后buf仲存储7654321.不打印!!c.倒置不允许使用辅助数组。
d.要求A线程打印出来的结果只能为1234567或者7654321e.不允许使用sleep函数
1 #include<stdio.h>
2 #include<time.h>
3 #include<pthread.h>
4 #include<string.h>
5 #include<unistd.h>
6 char buf[]="1234567";
7 //通过更改a的值,a=1循环逆序并使a=2,a=2时循环输出使得a=1
8 void *callBack(void *arg)
9 {
10 while(1)
11 {
12 //printf("%d\t%c",*(int *)arg,buf[0]);
13
14 if(*(int*)arg==2)
15 {
16 // printf("%d\n",*(int*)arg);
17 for(int i=0,j=strlen(buf)-1;i<j;i++,j--)
18 {
19 buf[i]=buf[i]+buf[j];
20 buf[j]=buf[i]-buf[j];
21 buf[i]=buf[i]-buf[j];
22 }
23 *(int *)arg=1;
24 }
25 }
26 }
27 int main(int argc, const char *argv[])
28 {
29 int a=2;
30 int *b=&a;
31 pthread_t ttid;
32 if(pthread_create(&ttid,NULL,callBack,b)!=0)
33 {
34 fprintf(stderr,"pthread_creat failed __%d__",__LINE__);
35 return -1;
36 }
37 while(1)
38 {
39 if(1==a)
40 {
41 fprintf(stdout,"%s\n",buf);
42 a=2;
43 }
44
45 }
46 return 0;
47 }
~
输出结果
1234567
7654321
1234567
7654321
1234567
7654321
1234567
7654321
1234567
7654321
1234567
7654321
1234567
7654321
1234567
7654321
1234567
7654321
1234567
7654321
1234567
7654321
1234567
7654321
^Z
[37]+ 已停止 ./a.out