#include<stdio.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
void* callBack(void* arg)
{
while(1)
{
time_t now=time(NULL);
struct tm *p =localtime(&now);
fprintf(stderr,"%4d-%02d-%02d %02d-%02d-%02d\r",\
p->tm_year+1900,p->tm_mon+1,p->tm_mday,\
p->tm_hour,p->tm_min,p->tm_sec);
}
}
int main(int argc, const char *argv[])
{
pthread_t tid;
if(pthread_create(&tid,NULL,callBack,NULL)!=0)
{
fprintf(stderr,"pthread_create failed __%d__\n",__LINE__);
return -1;
}
char str[10]="";
scanf("%s",str);
if(strcmp(str,"quit") == 0)
{
exit(0);
}
return 0;
}
要求定义一个全局变量char buf= "1234567",创建两个线程,不考虑退出条件。
#include<stdio.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
char buf[]="1234567";
void strev(char *p)
{
int i=0;int len=strlen(p)-1;
char t;
for(int i=0;i<len;i++)
{
t=*(p+i);*(p+i)=*(p+len);*(p+len)=t;
len--;
}
return;
}
void* callBackB(void* arg)
{
while(1)
{
strev(buf);
sleep(1);
}
}
int main(int argc,const char *argv[])
{ pthread_t tid;
if(pthread_create(&tid,NULL,callBackB,NULL)!=0)
{
fprintf(stderr,"pthread_create failed __%d__\n",__LINE__);
return -1;
}
while(1)
{
printf("%s\n",buf);
sleep(1);
}
return 0;
}
用线程拷贝图片
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <pthread.h>
int dp,dp1;
char c;
off_t size;
pthread_mutex_t mutex;
void *callBackA(void* arg)
{
pthread_mutex_lock(&mutex);
lseek(dp,0,SEEK_SET);
lseek(dp1,0,SEEK_SET);
for(int i=0;i<size;i++)
{
if(read(dp,&c,1)<0)
{
perror("read");
}
if(write(dp1,&c,1)<0)
{
perror("write");
}
}
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
void *callBackB(void* arg)
{
pthread_mutex_lock(&mutex);
lseek(dp,size,SEEK_SET);
lseek(dp1,size,SEEK_SET);
for(int i=0;i<size;i++)
{
if(read(dp,&c,1)<0)
{
perror("read");
}
if(write(dp1,&c,1)<0)
{
perror("write");
}
}
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
dp=open("./op.ing",O_RDONLY);
dp1=open("./cp.ing",O_RDWR|O_CREAT|O_TRUNC,0664);
size=lseek(dp,0,SEEK_END)/2;
pthread_t tid,tid1;
pthread_mutex_init(&mutex,NULL);
if(pthread_create(&tid,NULL,callBackA,NULL)<0)
{
perror("callBackA");
return -1;
}
pthread_join(tid,NULL);
if(pthread_create(&tid1,NULL,callBackB,NULL)<0)
{
perror("callBackB");
return -1;
}
pthread_join(tid1,NULL);
close(dp);
close(dp1);
pthread_mutex_destroy(&mutex);
return 0;
}