多線程程序的設計詳解


進程與線程:  

  進程是一個拷貝的流程,需要更大的系統開銷。具有互斥性,某一進程使用着資源其他均需等待

線程就是把一個進程分為多片,每一片都是一個獨立的流程,線程相較於進程沒有拷貝這些額外的系統開銷。他們共享着進程的代碼段、數據段,但每個線程都有屬於自己的堆、棧段。所以並發程序設計師常用多線程實現!

 

多線程程序設計基礎函數:

1)創建線程

int pthread_create(pthread_t *restrict tidp,               //存儲新創建線程的id,指針類型
                   const pthread_attr_t *restrict attr,    //創建線程的屬性,一般NULL
                   void *(*start_rtn)(void),               //線程的執行函數的入口地址
                   void *restrict arg);                    //執行函數的參數,一般NULL
  Returns: 0 if OK, error number on failure
eg: pthread_create(&thread[0], NULL, worker1, NULL);//worker1:線程的入口函數

2)等待線程

int pthread_join (pthread_t thread,void **retval);//要等待線程的id  保存線程退出時的狀態,一般為NULL
  Returns: 0 if OK, error number on failure
eg: pthread_join(thread[0], NULL);

 3)退出線程

void pthread_exit (void * retval);   //保存退出狀態,一般NULL
eg: pthread_exit(NULL); //退出線程

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

多線程互斥設計:

  實際中多線程同樣具有互斥性,會同時訪問同一資源->互斥鎖(信號量flag)

    pthread_mutex_t mut;//定義一個互斥鎖
 下列函數成功返回01)初始化互斥鎖 eg: pthread_mutex_init(&mut,NULL); int pthread_mutex_init( pthread_mutex_t* mut, ~ attr);   //互斥鎖的指針 指定互斥鎖屬性NULL
2)鎖住互斥鎖 eg: pthread_mutex_lock(&mut); int pthread_mutex_lock(pthread_mutex_t* mut);             //指明需要鎖住的互斥鎖
3)解開互斥鎖 eg: pthread_mutex_unlock(&mut); int pthread_mutex_unlock(pthread_mutex_t* mut);           //指明需要解開的互斥鎖

  一般多線程與互斥鎖配合使用,多線程共用全局變量,每個任務函數擁有獨自的堆棧,各自並行運行不打擾!

主程序中 :        初始化互斥鎖->創建多個線程(括入了線程函數)->等待多個線程結束->return 0;  此時多線程的任務函數已在后台並發運行,等待任務函數完成后程序退出;

線程任務函數中每個線程任務函數->使用各自的堆棧空間->鎖住互斥鎖->共用進程所有資源->解開互斥鎖->完成,退出線程;  多線程並發性的體現。

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 多線程同步設計:

   多個線程按照規定要求的順序來執行,即為線程同步。    設規定順序:線程A->線程B->任務完成

同步函數->相當於開關信號量   
設定外部全局變量: pthread_cond_t cond_ready = PTHREAD_COND_INITIALIZER; 1)條件成熟函數 pthread_cond_signal(&cond_ready); //線程A->調用此,運行后及條件成熟 2)等待條件成熟 pthread_cond_wait(&cond_ready,&mut); //線程B->等待狀態 本線程互斥鎖信號量

多線程互斥+同步函數=多線程同步

 主程序中 :        與多線程互斥相同;

線程任務函數中:與多線程互斥前后部分相同,僅僅一個地方!鎖住互斥鎖->共用進程所有資源->線程條件設定,實現順序功能->解開互斥鎖->  ;

   線程A滿足時,運行條件成熟函數pthread_cond_signal;線程B未等到線程A完成設定要求是,運行pthread_cond_wait一直等待。

 

/*多線程互斥*/
#include <pthread.h>
#include <stdio.h>

pthread_t thread[2];//保存線程1和2的id
int number  = 0;
pthread_mutex_t mut;//定義一個互斥鎖

void * worker1()
{
    int i = 0;
    printf("I am worker1!\n");
    
    for(i=0;i<10;i++)
    {
        pthread_mutex_lock(&mut);//加鎖
        
        number++;
        
        pthread_mutex_unlock(&mut);//解鎖
        
        printf("worker1 number is %d\n",number);
        sleep(1);    
    }
    pthread_exit(NULL);    //退出線程
}

void * worker2()
{
    int i = 0;
    printf("I am worker2!\n");
    
    for(i=0;i<10;i++)
    {
        pthread_mutex_lock(&mut);//加鎖
        
        number++;
        
        pthread_mutex_unlock(&mut);//解鎖
        
        printf("worker2 number is %d\n",number);
        sleep(1);    
    }
    pthread_exit(NULL);    //退出線程    
}

int main()
{
    pthread_mutex_init(&mut,NULL);//鎖的初始化,默認屬性
    
    /*創建工人1線程*/
    pthread_create(&thread[0], NULL, worker1, NULL);//worker1:線程的入口函數    
    
    /*創建工人2線程*/
    pthread_create(&thread[1], NULL, worker2, NULL);
    
    /*等待工人1線程的結束*/
    pthread_join(thread[0], NULL);
    
    /*等待工人2線程的結束*/
    pthread_join(thread[1], NULL);
    
    return 0;
}
View Code
/*多線程同步*/
#include <pthread.h> 
#include <stdio.h>

pthread_t thread[2];
int number = 0;
pthread_mutex_t mut;

pthread_cond_t cond_ready=PTHREAD_COND_INITIALIZER;

void * studentA()
{
    int i;
    
    for(i=0;i<5;i++)
    {
        pthread_mutex_lock(&mut);
        /*掃一次地*/
        number++;
        
        if (number >=5)
        {
            printf("student A has finished his work!\n");
            /*通知B同學*/
            pthread_cond_signal(&cond_ready);
            
        }   
        pthread_mutex_unlock(&mut);
        
        /*休息1秒鍾*/
        sleep(1);    
    }    
    /*退出*/
    pthread_exit(NULL);
}

void * studentB()
{
        pthread_mutex_lock(&mut);
        
        if(number<5)/*判斷A同學是否已經掃完5次地*/
            pthread_cond_wait(&cond_ready,&mut);
            
            /*拖地*/
            number = 0;
            
            pthread_mutex_unlock(&mut);
            printf("student B has finished his work!\n");
    
    /*退出*/
    pthread_exit(NULL);    
}

int main()
{
    /*初始化互斥鎖*/
    pthread_mutex_init(&mut,NULL);
    
    /*創建A同學線程*/
    pthread_create(&thread[0], NULL, studentA, NULL);
    
    /*創建B同學線程*/
    pthread_create(&thread[1], NULL, studentB, NULL);    
    
    /*等待A同學線程結束*/
    pthread_join(thread[0], NULL); 
    
    /*等待B同學線程結束*/
    pthread_join(thread[1], NULL); 
}
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM