. A线程 循环 打印str字符串。
2. B线程 循环 倒置str字符串,不使用辅助数组。注意是循环倒置,要把字符串倒过来,倒回去。
3. 要求A线程打印出来的结果是有序的
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <semaphore.h>
sem_t sem;
char str[]="123456";
//打印线程
void *callback_printf(void *arg)
{
//申请信号量P操作
if(sem_wait(&sem)<0)
{
perror("sem_wait");
}
while(1)
{
printf("%s\n", str);
}
//信号量V操作
if(sem_post(&sem)<0)
{
perror("sem_post");
}
pthread_exit(NULL);
}
//负责倒置的线程
void *callback_reserve(void *arg)
{
int temp;
int i=0;
//信号量p操作
if(sem_wait(&sem)<0)
{
perror("sem_wait");
}
while(1)
{
for(i=0; i<strlen(str)/2; i++)
{
temp=str[i];
str[i]=str[strlen(str)-1-i];
str[strlen(str)-1-i]=temp;
}
printf("%s\n", str);
}
//信号量V操作
if(sem_post(&sem)<0);
{
perror("sem_post");
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//创建具有互斥锁性质的信号量
if(sem_init(&sem, 0, 1)<0)
{
perror("sem_init");
return -1;
}
//创建两个线程
pthread_t tid1, tid2;
//一个线程负责打印
if(pthread_create(&tid1, NULL, callback_printf, NULL)!=0)
{
perror("pthread_create");
return -1;
}
//一给负责倒置
if(pthread_create(&tid1, NULL, callback_reserve, NULL)!=0)
{
perror("pthread_create");
return -1;
}
//阻塞函数退出
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
if(sem_destroy(&sem)<0)
{
perror("sem_destroy");
}
return 0;
}