int sem_destroy(sem_t *sem)
函数传入值 sem:信号量
函数返回值 成功:0 ,出错:-1
从上面函数来看,实现线程之间同步信号量比互斥锁使用起来相对容易一些,操作简单,容易理解,适用范围广。
下面上一篇的问题用信号量来实现,线程使用部分没变,主要改变了对资源的控制方式:(代码本人亲自编译通过)
view plaincopy to clipboardprint?
01.#i nclude
02.#i nclude
03.#i nclude
04.#i nclude
05.#i nclude
06.#i nclude
07.
08.int g_Flag = 0;
09.sem_t sem_mutex; // 用于互斥
10.sem_t sem_syn; // 用于同步
11.
12.void *thread1( void *arg );
13.void *thread2( void *arg );
14.int main()
15.{
16. pthread_t tid1, tid2;
17. int rc1, rc2;
18.
19. sem_init( &sem_mutex, 0, 1 );
20. sem_init( &sem_syn, 0, 0 );
21. printf( “ Inter main !n” );
22.
23. rc2 = pthread_create( &tid2, NULL, thread2, NULL );
24. if( rc2 != 0 )
25. printf( “ %s, %d n”, __func__, strerror( rc2 ) );
26.
27. rc1 = pthread_create( &tid1, NULL, thread1, &tid2 );
28. if( rc1 != 0 )
29. printf( “ %s, %d n”, __func__, strerror(rc1) );
30. printf( “ Leave main!nn” );
31.
32. sem_wait( &sem_syn ); // 同步等待,阻塞
33. exit( 0 );
34.}
35.
36.void *thread1( void *arg )
37.{
38. pthread_t *ptid = NULL;
39. printf( “ Enter thread1n” );
40. printf( “ thread1 id: %u, g_Flag: %d n”, ( unsigned int )pthread_self(), g_Flag );
41.
42. if( sem_wait( &sem_mutex ) != 0)
43. {
44. perror(“ pthread1 sem_mutexn”);
45. }
46.
47. if( g_Flag == 2 )
48. sem_post( &sem_syn );
49. g_Flag = 1;
50.
51. if( sem_post( &sem_mutex ) != 0)
52. {
53. perror( “pthread1 sem_postn” );
54. }
55. printf( “ thread1 id: %u, g_Flag: %d n”,( unsigned int )pthread_self(), g_Flag );
56. printf( “Leave thread1 nn” );
57.
58. ptid = ( pthread_t *)arg;
59. printf( “ ptid = %u n”, *ptid );
60. pthread_join( *ptid, NULL );
61. pthread_exit(0 );
62.}
63.
64.void *thread2( void *arg )
65.{
66. printf( “ Enter thread2 !n” );
67. printf( “ thread2 id: %u , g_Flag: %d n”, ( unsigned int)pthread_self(), g_Flag );
68.
69. if( sem_wait( &sem_mutex ) != 0 )