要求定义一个全局变量 char buf[] = "1234567",创建两个线程,不考虑退出条件,另:
- A线程循环打印buf字符串,
- B线程循环倒置buf字符串,即buf中本来存储1234567,倒置后buf中存储7654321. 不打印!!
- 倒置不允许使用辅助数组。
- 要求A线程打印出来的结果只能为 1234567 或者 7654321 不允许出现7634521 7234567
- 不允许使用sleep函数
方法一:使用flag将其分离
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <head.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread.h>char buf[]="1234567";
int flag= 0 ;void* callback_1(void* arg)//打印
{while(1){if(0 == flag){printf("%s\n",buf);flag=1;}}pthread_exit(NULL);
}void* callback_2(void* arg)//逆置 不打印
{char t=0;while(1){if(1 == flag){for(int i=0;i<strlen(buf)/2;i++){t=buf[i];buf[i] = buf[strlen(buf)-1-i];buf[strlen(buf)-1-i] = t;}flag=0;}}pthread_exit(NULL);
}int main(int argc, const char *argv[])
{pthread_t tid_1,tid_2;if(pthread_create(&tid_1,NULL,callback_1,NULL)!=0){fprintf(stderr,"pthread_create failed __%d__\n",__LINE__);return -1;}pthread_detach(tid_1); //分离线程1if(pthread_create(&tid_2,NULL,callback_2,NULL)!=0){fprintf(stderr,"pthread_create failed __%d__\n",__LINE__);return -1;}pthread_join(tid_2,NULL);printf("主线程准备退出");return 0;
}
方法二:使用互斥锁
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <head.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread.h>
//临界资源
char buf[]="1234567";//互斥锁
pthread_mutex_t mutex;void* callback_1(void* arg)//打印
{while(1){/***********临界区**************///上锁pthread_mutex_lock(&mutex);printf("%s\n",buf);//解锁pthread_mutex_unlock(&mutex);/***********临界区**************/}pthread_exit(NULL);
}void* callback_2(void* arg)//逆置 不打印
{char t=0;while(1){/***********临界区**************///上锁pthread_mutex_lock(&mutex);for(int i=0;i<strlen(buf)/2;i++){t=buf[i];buf[i] = buf[strlen(buf)-1-i];buf[strlen(buf)-1-i] = t;}//解锁pthread_mutex_unlock(&mutex);/***********临界区**************/}pthread_exit(NULL);
}int main(int argc, const char *argv[])
{//申请一个互斥锁pthread_mutex_init(&mutex,NULL);pthread_t tid_1,tid_2;if(pthread_create(&tid_1,NULL,callback_1,NULL)!=0){fprintf(stderr,"pthread_create failed __%d__\n",__LINE__);return -1;}pthread_detach(tid_1); //分离线程1if(pthread_create(&tid_2,NULL,callback_2,NULL)!=0){fprintf(stderr,"pthread_create failed __%d__\n",__LINE__);return -1;}pthread_join(tid_2,NULL); //阻塞等待线程2退出//销毁互斥锁pthread_mutex_destroy(&mutex);return 0;
}