#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <semaphore.h>
sem_t sem;
char buf[] = "1234567";
void* callback1(void* arg)
{
while(1)
{
sem_wait(&sem);
printf("%s\n",buf);
sleep(1);
sem_post(&sem);
}
pthread_exit(NULL);
}
void* callback2(void *arg)
{
int len = strlen(buf);
char temp;
int j;
while(1)
{
sem_wait(&sem);
for(int i =0,j = len-1;i<j;i++,j--)
{
temp = buf[i];
buf[i] = buf[j];
buf[j] = temp;
}
sleep(1);
sem_post(&sem);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
sem_init(&sem,0,2);
pthread_t tid1,tid2;
pthread_create(&tid1,NULL,callback1,NULL);
pthread_create(&tid2,NULL,callback2,NULL);
pthread_detach(tid2);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
sem_destroy(&sem);
return 0;
}
运行结果: