1 #include <pthread.h> 2 #include <semaphore.h> 3 #include <stdio.h> 4 5 static sem_t sema; 6 static void* other_thread() 7 { 8 printf("other_thread here!\n"); 9 10 sleep(1); 11 12 while (1) 13 { 14 printf("other_thread: sem_post...\n"); 15 if(sem_post(&sema) == -1) 16 printf("sem_post failed\n"); 17 sleep(1); 18 } 19 20 printf("other_thread dies!\n"); 21 pthread_exit(0); 22 } 23 24 static void test_thread(void* parameter) 25 { 26 pthread_t tid; 27 28 printf("main thread here!\n"); 29 printf("sleep 5 seconds..."); 30 sleep(5); 31 printf("done\n"); 32 33 sem_init(&sema, 0, 0); 34 35 /* create the "other" thread */ 36 if(pthread_create(&tid, 0, &other_thread, 0)!=0) 37 /* error */ 38 printf("pthread_create OtherThread failed.\n"); 39 else 40 printf("created OtherThread=%x\n", tid); 41 42 /* let the other thread run */ 43 while (1) 44 { 45 printf("Main: sem_wait...\n"); 46 if(sem_wait(&sema) == -1) 47 printf("sem_wait failed\n"); 48 printf("Main back.\n\n"); 49 } 50 51 pthread_exit(0); 52 } 53 #include <finsh.h> 54 void libc_sem() 55 { 56 rt_thread_t tid; 57 58 tid = rt_thread_create("semtest", test_thread, RT_NULL, 59 2048, 20, 5); 60 if (tid != RT_NULL) 61 { 62 rt_thread_startup(tid); 63 } 64 } 65 FINSH_FUNCTION_EXPORT(libc_sem, posix semaphore test); 66