1. 修改标准IO时候写的时钟代码,要求输入'q'后,能够退出该程序。
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
void *pthrcell(void *arg)
{
FILE *fp=fopen("time.txt","a+");
int num=1,a;
while((a=fgetc(fp))!=-1){
if(a=='\n'){
num++;
}
}
while(1){
size_t t=time(NULL);
struct tm *ct=localtime(&t);
fprintf(fp,"[%d] %02d-%02d-%02d %02d:%02d:%02d\n",
num,\
ct->tm_year+1900,\
ct->tm_mon+1,\
ct->tm_mday,\
ct->tm_hour,\
ct->tm_min,\
ct->tm_sec);
fflush(fp);
num++;
sleep(1);
}
fclose(fp);
return 0;
}
int main(int argc, const char *argv[])
{
pthread_t tpid;
if(pthread_create(&tpid,NULL,pthrcell,NULL)){
perror("pthread_cread:");
return 0;
}
char c=0;
while(1){
c=fgetc(stdin);
if(c=='q'){
break;
}
}
return 0;
}
2. 要求创建两个线程,以及一个全局变量,char str[] = "123456"
要求如下:
1)一个线程专门用于打印str;
2)另外一个线程专门用于倒置str字符串,不使用辅助数组。
3)要求打印出来的结果必须是123456或者654321,不能出现乱序情况
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <errno.h>
char str[]="123456";
void *pth1cell(void *arg) // 打印子线程
{
while(1){
printf("%s\n",str);
sleep(1);
}
}
void *pth2cell(void *arg) // 翻转子线程
{
long long rev=0x676767676767; // 0x67='1'+'6'
long long *aid=(long long *)str;
while(1){
*aid=rev-*aid;
sleep(1);
}
}
int main(int argc, const char *argv[])
{
pthread_t tpid1,tpid2;
if(pthread_create(&tpid1,NULL,pth1cell,NULL)){
perror("tpid1:");
return 0;
}
if(pthread_create(&tpid2,NULL,pth2cell,NULL)){
perror("tpid2:");
return 0;
}
while(1);
return 0;
}