linux--線程操作

概念:線程是共享進程地址空間的多任務結構

創建線程的相關函數

1. int pthread_create(pthread_t *thread, const pthread_attr_t *attr,

                          void *(*start_routine) (void *), void *arg);

                        參數1 :線程ID指針

                        參數2 :線程屬性,使用時通常爲NULL

                        參數3 :線程函數指針

                        參數4 :線程函數入參

                        返回值:0 成功,-1 失敗

                        頭文件:  #include <pthread.h>

2. int pthread_join(pthread_t thread, void **retval);

                        參數1:等待退出的線程ID

                        參數2:線程的結束信息,通常爲NULL,不爲NULL時注意參數爲void, 需要與pthread_exit配合使用。

                        返回值:0 成功,-1 失敗

                        頭文件: #include <pthread.h>

3.int  pthread_mutex_init(pthread_mutex_t  *mutex,

                        pthread_mutexattr_t *attr)

                      功  能:初始化鎖

                     參數1:初始化的鎖

                     參數2:鎖屬性,使用時通常爲空,使用默認屬性

                     返回值:0 成功,-1 失敗

                     頭文件: #include <pthread.h>

4.int  pthread_mutex_lock(pthread_mutex_t *mutex)  

                    功能:加鎖

                    參數1:鎖

                    返回值:0 成功, -1 失敗

                頭文件: #include <pthread.h>

5.int  pthread_mutex_unlock(pthread_mutex_t *mutex)

                    功能:解鎖

                    參數1:鎖

                    返回值:0 成功, -1 失敗

                    頭文件:#include <pthread.h>

6.int sem_init(sem_t *sem, int pshared, unsigned int value);

                    功能:初始化信號燈

                   參數1:被初始化的信號燈

                  參數2:使用範圍,0線程範圍內使用, 1進程範圍內使用

                  參數3:信號燈持有資源個數

                 返回值:0 成功, -1失敗

                頭文件:#include <semaphore.h>

7. int  sem_wait(sem_t *sem)

                 功能:申請資源,申請成功後信號燈的資源個數減1,當資源個數爲0時阻塞

               參數1:信號燈指針

               返回值:0 成功, -1失敗

               頭文件:#include <semaphore.h>

8.int  sem_post(sem_t *sem)

               功能:釋放資源,釋放成功後信號燈的資源個數加1,釋放資源後喚醒等待的線程

              參數1:信號燈指針

              返回值:0 成功, -1失敗

             頭文件:#include <semaphore.h>

信號量:就是一種資源,定義信號量時需要指定此信號持有資源的個數,爲非負整數

p:申請資源,將信號量持有資源個數減一

   申請不到資源時等待。

v:釋放資源,將信號量持有資源個數加一。


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