2021-03-08 07:18:51 +08:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2006-2021, RT-Thread Development Team
|
|
|
|
*
|
|
|
|
* SPDX-License-Identifier: Apache-2.0
|
|
|
|
*
|
|
|
|
* Change Logs:
|
|
|
|
* Date Author Notes
|
|
|
|
*/
|
|
|
|
|
2013-01-08 21:05:02 +08:00
|
|
|
#include <pthread.h>
|
|
|
|
#include <semaphore.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
|
|
|
|
static sem_t sema;
|
|
|
|
static void* other_thread()
|
|
|
|
{
|
2021-03-07 08:34:04 +08:00
|
|
|
printf("other_thread here!\n");
|
2013-01-08 21:05:02 +08:00
|
|
|
|
2021-03-07 08:34:04 +08:00
|
|
|
sleep(1);
|
2013-01-08 21:05:02 +08:00
|
|
|
|
2021-03-07 08:34:04 +08:00
|
|
|
while (1)
|
|
|
|
{
|
|
|
|
printf("other_thread: sem_post...\n");
|
|
|
|
if(sem_post(&sema) == -1)
|
|
|
|
printf("sem_post failed\n");
|
|
|
|
sleep(1);
|
|
|
|
}
|
|
|
|
|
|
|
|
printf("other_thread dies!\n");
|
|
|
|
pthread_exit(0);
|
2013-01-08 21:05:02 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
static void test_thread(void* parameter)
|
|
|
|
{
|
2021-03-07 08:34:04 +08:00
|
|
|
pthread_t tid;
|
|
|
|
|
|
|
|
printf("main thread here!\n");
|
|
|
|
printf("sleep 5 seconds...");
|
|
|
|
sleep(5);
|
|
|
|
printf("done\n");
|
2013-01-08 21:05:02 +08:00
|
|
|
|
2021-03-07 08:34:04 +08:00
|
|
|
sem_init(&sema, 0, 0);
|
2013-01-08 21:05:02 +08:00
|
|
|
|
2021-03-07 08:34:04 +08:00
|
|
|
/* create the "other" thread */
|
|
|
|
if(pthread_create(&tid, 0, &other_thread, 0)!=0)
|
|
|
|
/* error */
|
|
|
|
printf("pthread_create OtherThread failed.\n");
|
|
|
|
else
|
|
|
|
printf("created OtherThread=%x\n", tid);
|
2013-01-08 21:05:02 +08:00
|
|
|
|
2021-03-07 08:34:04 +08:00
|
|
|
/* let the other thread run */
|
|
|
|
while (1)
|
|
|
|
{
|
|
|
|
printf("Main: sem_wait...\n");
|
|
|
|
if(sem_wait(&sema) == -1)
|
|
|
|
printf("sem_wait failed\n");
|
|
|
|
printf("Main back.\n\n");
|
|
|
|
}
|
2013-01-08 21:05:02 +08:00
|
|
|
|
2021-03-07 08:34:04 +08:00
|
|
|
pthread_exit(0);
|
2013-01-08 21:05:02 +08:00
|
|
|
}
|
|
|
|
#include <finsh.h>
|
|
|
|
void libc_sem()
|
|
|
|
{
|
2021-03-07 08:34:04 +08:00
|
|
|
rt_thread_t tid;
|
2013-01-08 21:05:02 +08:00
|
|
|
|
2021-03-07 08:34:04 +08:00
|
|
|
tid = rt_thread_create("semtest", test_thread, RT_NULL,
|
|
|
|
2048, 20, 5);
|
|
|
|
if (tid != RT_NULL)
|
|
|
|
{
|
|
|
|
rt_thread_startup(tid);
|
|
|
|
}
|
2013-01-08 21:05:02 +08:00
|
|
|
}
|
|
|
|
FINSH_FUNCTION_EXPORT(libc_sem, posix semaphore test);
|