一个时钟代码,以输入quit作为结束
#include <stdio.h>
#include <time.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
void *show_time(void *arg){
time_t t;
struct tm *tm;
while(1){
t = time(NULL);
tm = localtime(&t);
printf("%d-%02d-%02d %02d:%02d:%02d\r",tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec);
fflush(stdout);
sleep(1);
}
return NULL;
}
int main(int argc, const char *argv[])
{
pthread_t tid;
if(pthread_create(&tid,NULL,show_time,NULL)){
fprintf(stdout,"Thread creation failed\n");
return 0;
}
char str[20] = "";
while(1){
scanf("%s",str);
if(strcmp(str,"quit") == 0){
break;
}
}
return 0;
}
一个全局变量char *buf = “1234567”
创建两个线程
线程a 循环打印buf
线程b 在不用辅助数组的情况下逆置buf
只允许出现1234567 和 7654321
不允许使用sleep
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
static char buf[7] = "1234567";
void *second_thread(void *arg){
int len = sizeof(buf);
char *head = buf;
char *tail = buf + len -1;
while(head < tail){
char temp = *head;
*head = *tail;
*tail = temp;
head++;
tail--;
}
//printf("%s\n",buf);
pthread_exit(NULL);
}
void *first_thread(void *arg){
pthread_t tid_b;
while(1){
if(pthread_create(&tid_b,NULL,second_thread,NULL)){
fprintf(stdout,"%d Thread creation failed.\n",__LINE__);
}
pthread_join(tid_b,NULL);
printf("%s\n",buf);
}
}
int main(int argc, const char *argv[])
{
pthread_t tid_a;
if(pthread_create(&tid_a,NULL,first_thread,NULL) != 0){
fprintf(stdout,"%d Thead creation failed.\n",__LINE__);
return 0;
}
while(1){
}
return 0;
}