undefined.在循环打印倒置那题的条件基础上用信号量实现,打印一次,倒置一次。.提示:用两个信号量,一个初始化为1,另外一个初始化为0
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>
#include <unistd.h>
char buf[] = "1234567";
sem_t max;
int flag = 0;
void* callBack1(void* arg)
{
while(1)
{
if(sem_wait(&max) < 0)
{
perror("sem_wait");
pthread_exit(NULL);
}
if(flag == 0)
{
printf("%s\n",buf);
flag = 1;
}
if(sem_post(&max) < 0)
{
perror("sem_post");
pthread_exit(NULL);
}
}
pthread_exit(NULL);
}
void* callBack2(void* arg)
{
char temp;
int i,j;
while(1)
{
if(sem_wait(&max) < 0)
{
perror("sem_wait");
pthread_exit(NULL);
}
if(flag == 1)
{
for(int i=0,j=strlen(buf)-1;i<j;i++,j--)
{
temp = buf[i];
buf[i] = buf[j];
buf[j] = temp;
}
flag = 0;
}
if(sem_post(&max) < 0)
{
perror("sem_post");
pthread_exit(NULL);
}
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
if(sem_init(&max,0,2) < 0)
{
perror("sem_init");
return -1;
}
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,callBack1,NULL) != 0)
{
fprintf(stderr,"__%d__\n",__LINE__);
return -1;
}
if(pthread_create(&tid2,NULL,callBack2,NULL) != 0)
{
fprintf(stderr,"__%d__\n",__LINE__);
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
sem_destroy(&max);
return 0;
}
运行结果
原文地址:https://blog.csdn.net/2201_75900260/article/details/136460842
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!