Linux GCC 開發入門(4) -- pthread多線程 初步 semaphore

多線程 是 Linux 編程必備。編程接口上 自然是支持 最多的 POSIX pthread. 

1.線程的產生:    pthread_create   可以立刻運行一個  void * thread_func(void *) 的線程。

2.線程通訊: 互斥保護 pthread_mutex_t,     條件信號 pthread_cond_t.    

                       pthread_mutex_t  和widnows下的CRITICAL_SECTION 完全相同。

                       但是看文檔 cond用起來 怪怪的。

                       a. cond 無論廣播 還是 單個觸發信號, 都針對正在等待cond的線程有效。 如果觸發之後,線程再等待則無效。  (why?)

                       b. cond 等待 還要一個mutex 配合。  (不明白,其中的道理)


倒是 semaphore, 發現這個和widnows下的表現最一致。

 測試程序

      1. 子線程  等待 信號量

      2. 主線程 調用    sem_destroy  是否 會 使 等待的線程產生錯誤。 

測試結果

     LINUX下, 子線程不受sem_destroy  的影響。 一直處於等待狀態。 



    #include <iostream>
    #include <map>
    using namespace std;
    #include <semaphore.h>
    #include <sys/unistd.h>

    #include <pthread.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <mqueue.h>

    sem_t  g_sem;

    const char * ret_msg[] =
    {
    		"sem thread exit!",
    		"cond thread exit!",
    		"que thread exit!"
    };


    const char *  in_msg[] = { "t1", "t2", "t3"} ;


    void *thread_sem(void *arg)
    {
        int iwait ;
        sleep( 1 );
        printf("  [1]child_sem is running. Argument was %s\n", (char *)arg );
        printf("  [1]If main destroy sem, child wait will return? \n"  );
        printf("  [1]child_sem waiting for sem..........  \n" );
        iwait = sem_wait( &g_sem );
        if ( iwait == 0 )
        {
            printf("  [1]child_sem waiting return OK! \n" );
        }
        else
        {
            printf("  [1]child_sem waiting return error!  %d\n", iwait );
        }

        pthread_exit(  (void *)ret_msg[0] );
    }
	int main()
	{
        int res, ifunc, csel;
        pthread_t t1, t2, t3;
        void *thread_result;

        sem_init( &g_sem , 0, 0 );
        printf("create thread_sem \n");

        res = pthread_create(&t1, NULL, thread_sem, (void *)in_msg[1]);

        sleep( 2 );
        printf("\n\ninput \n1.destroy\n2.sem_post \nTo see what happens!...\n");


        do
        {
        csel =  getchar();
        }while( csel == '\n' );

        printf("\nyou choose: %c\nwhat happens here!\n", csel );

        if ( csel == '1')
        {
             ifunc = sem_destroy( &g_sem );
           	 printf( "Destroy semaphore:  %d\n", ifunc  );
        }
        else
        {
             ifunc = sem_post( &g_sem );
             printf( "Post semaphore:  %d\n", ifunc  );
        }



        printf("join Thread_sem .......\n");
        res = pthread_join( t1, &thread_result);
        printf("Thread_sem joined,  %d  %s\n", res, (char *)thread_result);

        exit(EXIT_FAILURE);
    }





結果


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章