#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
//int flag = 1;
sem_t sem;
sem_t sem1;
void *thread_function(void *arg);
int main()
{
int res;
pthread_t a_thread;
void *thread_result;
int count = 1;
res = sem_init(&sem, 0, 0);
res = sem_init(&sem1, 0, 0);
res = pthread_create(&a_thread, NULL, thread_function, NULL);
if (res != 0)
{
perror("Thread creation failed");
exit(EXIT_FAILURE);
}
while (count++ <= 20)
{
printf ("1\n");
sem_post(&sem);
sem_wait(&sem1);
}
printf("Waiting for thread to finish...\n");
res = pthread_join(a_thread, &thread_result);
if (res != 0)
{
perror("Thread join failed");
exit(EXIT_FAILURE);
}
sem_destroy(&sem);
sem_destroy(&sem1);
exit(EXIT_SUCCESS);
}
void *thread_function(void *arg)
{
int count = 1;
while (count++ <= 20)
{
sem_wait(&sem);
printf("2\n");
sem_post(&sem1);
}
}
Andoird基础Thread6.Linux 循环sem_t实现 数字循环
最新推荐文章于 2022-12-08 17:18:43 发布