Linux C多線程編程-線程互斥


Linux下的多線程編程需要注意的是程序需要包含頭文件pthread.h,在生成可執行文件的時候需要鏈接庫libpthread.a或者libpthread.so

線程創建函數:

pthread_create(pthread_t *thread, pthread_attr_t * attr, void *(*start_routine)(void *),void *arg);

參數說明:

Thread 標示一個線程,它是一個pthread_t類型的變量(unsigned long int

attr 用於設置線程的屬性,默認是null

start_routine當線程分配資源成功后,線程中所運行的單元,通俗的說就是你自己寫的一個函數

Arg線程函數運行時傳入的一個參數,一般可以用這個傳入的參數去控制線程結束

函數返回值:

創建成功返回0,創建失敗返回非0值,常見錯誤返回代碼為EAGAINEINVALEGAIN標示系統中線程的數量達到上限,錯誤代碼EINVAL表示線程的屬性非法。

注意:線程創建城成功后,新創建的線程按照參數3和參數4確定一個運行函數,原來的線程在線程創建函數返回后繼續運行下一行代碼。

 

 

線程結束函數:pthread_join()和pthread_exit()

pthread_join()用來等待一個線程運行結束。這個函數是阻塞函數,一直被等待的線程結束為止,函數才返回並且收回被等待線程的資源。函數的原型為:

Extern int pthread_join_P((pthread_t _th,void **__thread_return));

_th:線程的標示符,也就是線程創建成功的值,在通俗的說就是pthread_create函數運行成功后的第一個參數

__thread_return:返回值,它是一個指針用來存貯被等待線程的返回值。

 

線程函數的結束方式有兩種:一種是線程函數運行結束,不用返回結果;另一種就是通過函數pthread_exit()來實現,將結果傳出。

函數原型是:

Extern void pthread_exit_P((void*_retval))

參數是函數的返回值,這個值可以被pthread_join函數捕獲,通過__thread_return參數獲得此值。

 

說道線程的創建還有一點必須要提及,那就是線程的屬性。一般在我們創建線程的時候設置attr屬性的時候都是使用null,這個是默認參數。但是在很多時候需要調整線程的屬性,特別是線程優先級。

線程的屬性結構為:pthread_attr_t,在頭文件<pthreadtype.h>中定義

typedef struct

{

       int                              detachstate;   線程的終止狀態

       int                              schedpolicy;  線程調度策略(優先級)

       struct sched_param           schedparam;  線程的調度參數

       int                              inheritsched;  線程的繼承性

       int                               scope;       線程的作用域

       size_t                          guardsize;   線程棧末尾的警戒緩沖區大小

       int                               stackaddr_set;  運行棧

       void *                         stackaddr;   線程棧的位置

       size_t                          stacksize;    線程棧的大小

}pthread_attr_t;

要注意的是線程的屬性值不能直接設置,必須要用先關的函數進行操作。線程屬性的初始化函數pthread_attr_init(),這個函數必須在pthread_create()函數之前調用。

線程間的互斥:

線程的互斥函數有:互斥函數的初始化pthread_mutex_init(),互斥函數的鎖定函數pthread_mutex_lock(),互斥函數的預鎖定函數pthread_mutex_trylock(),互斥函數的解鎖函數pthread_mutex_unlock(),互斥函數的銷毀函數pthread_mutex_destroy()

 

廢話不多說,上代碼:

#include <stdio.h>

#include <pthread.h>

 #include <unistd.h>

#define MUXNUMBER 10

pthread_mutex_t test_mutex;

int testi = 0;

int testis[10 * 1000];

int count=0;

 

void testfun(void)

{

testis[testi] = testi * 2;

usleep(1000);

testi++;

}

 

void thread_func()

{

    int m_count=0;

   while(m_count<1000)

   {

       pthread_mutex_lock(&test_mutex);

       testfun();

       pthread_mutex_unlock(&test_mutex);

       m_count++;

       //sleep(1);

   }

}

 

int main()

{

    pthread_t t[10];

    pthread_mutex_init(&test_mutex,NULL);

    int i;

    for(i=0;i<MUXNUMBER;i++)

    {

        if(pthread_create(&t[i],NULL,(void*)thread_func,NULL) == -1)

        {

            printf("create  Thread error !\n");

            exit(1);

        }

        //sleep(1);

    }

 

    for(i=0;i<MUXNUMBER;i++)

    {

         pthread_join(t[i],NULL);

        //sleep(1);

    }

 

    pthread_mutex_destroy(&test_mutex);

    for(i=0;i<10000;i++)

    {

        if(testis[i]!=i*2)

        {

            printf("%d個數據出錯!:%d\n",i,testis[i]);

        }

 

    }

    return 0;

}

簡單說下程序功能:程序創建十個線程,每個線程都調用testfun,通過互斥鎖保證數據的正常。

代碼比較簡單,僅僅只是為了讓讀者強化下前面看的一些概念性的東西。


免責聲明!

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



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