循环打印字符串,在使用线程的基础上,用信号量实现,打印一次,倒置一次。
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>
char buf[] = "A1234567B";
//信号量
sem_t sem;
sem_t sem2;
//aa线程的执行体
void* test_a(void* arg)
{
while(1)
{
//p操作 -1
if(sem_wait(&sem) < 0)
{
perror("sem_wait");
//pthread_exit(NULL);
}
//v操作 +1
if(sem_post(&sem2) < 0)
{
perror("sem_post");
//pthread_exit(NULL);
}
printf("buf = %s\n", buf);
}
pthread_exit(NULL);
}
//bb线程的执行体
void* test_b(void* arg)
{
int i;
int j = strlen(buf);
char temp = 0;
while(1)
{
//p操作 -1
if(sem_wait(&sem2) < 0)
{
perror("sem_wait");
//pthread_exit(NULL);
}
for(i=0; i<=j/2; i++)
{
temp = buf[i];
buf[i] = buf[j-1-i];
buf[j-1-i] = temp;
}
//v操作 +1
if(sem_post(&sem) < 0)
{
perror("sem_post");
//pthread_exit(NULL);
}
//printf("buf = %s\n", buf);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//创建并初始化信号量
if( sem_init(&sem, 0, 1) < 0)
{
perror("sem_init");
return -1;
}
if( sem_init(&sem2, 0, 0) < 0)
{
perror("sem2_init");
return -1;
}
//创建线程aa
pthread_t aa;
if( pthread_create(&aa, NULL, test_a, NULL) != 0)
{
fprintf(stderr, "pthread_create cuowu __%d__\n",__LINE__);
return -1;
}
//创建线程bb
pthread_t bb;
if( pthread_create(&bb, NULL, test_b, NULL) != 0)
{
fprintf(stderr, "pthread_create cuowu __%d__\n",__LINE__);
return -1;
}
pthread_join(aa,NULL); //阻塞等待
pthread_join(bb,NULL); //阻塞等待
//销毁信号量
sem_destroy(&sem);
sem_destroy(&sem2);
return 0;
}