Linux 线程及线程间通信
- 線程
- 1.線程相關接口函數(shù)
- 1)創(chuàng)建線程
- 2)結束線程
- 3)等待線程
- 2.線程間通信
線程
每一個進程的地址空間是相互獨立的
每一個進程都有一個task_struct任務結構體
在進行進程的切換時,需要不斷刷新cache緩存,比較消耗資源;
為了減少cache刷新時的資源消耗,引入了輕量級進程 – 線程。
線程特點:
進程被稱為最小的資源分配單位
線程稱為CPU最小任務調度單位
線程公共數(shù)據(jù):
- 用戶名、用戶組名
- 靜態(tài)數(shù)據(jù)、全局數(shù)據(jù)
- 文件描述符
- 線程私有數(shù)據(jù)
線程私有數(shù)據(jù):
- 線程ID
- PC
- 優(yōu)先級、狀態(tài)、屬性
- 堆棧
1.線程相關接口函數(shù)
pthread_create() 創(chuàng)建進程 pthread_exit 結束進程 pthread_join 等待進程在編譯跟線程操作相關的程序時,需要鏈接線程庫 線程庫庫名pthread
1)創(chuàng)建線程
#include <pthread.h> int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);返回值:成功返回 0,失敗返回錯誤號 參數(shù):thread: 線程對象attr: 線程屬性,填NULL表示使用默認屬性start_routine: 線程處理函數(shù) arg: 給線程處理函數(shù)start_routine傳參,若線程處理函數(shù)沒有參數(shù),則填NULL; /* 線程創(chuàng)建 傳入多個參數(shù) 舉例 */ void *func1(void *arg); struct m_arg {int a;char b; }pthread_t thread1; struct m_arg arg; arg.a = 1; arg.b = 'A';int ret = pthread_create(&thead1, NULL, func1, &arg);2)結束線程
#include <pthread.h> void pthread_exit(void *retval);參數(shù):retval: 線程結束信息,由pthread_join等待接收,若不想返回信息,填NULL3)等待線程
#include <pthread.h> int pthread_join(pthread_t thread, void **retval); //等待線程一般在主線程中調用2.線程間通信
線程的通信只需要利用全局變量就可以實現(xiàn)。
在一個線程使用全局變量時,有可能其他線程也在訪問該數(shù)據(jù),那么某一線程使用的數(shù)據(jù)就可能遭到破壞。
初始化信號量 sem_init()
#include <semaphore.h> int sem_init(sem_t *sem, int pshared, unsigned int value); 返回值:成功返回 0, 失敗返回 -1; 參數(shù):sem: 信號量對象;pshared: 填0表示用于線程間同步value: 信號量初始值P操作 sem_wait()
#include <semaphore.h> int sem_wait(sem_t *sem);V操作 sem_post()
#include <semaphore.h> int sem_post(sem_t *sem);通過線程的 同步 和 互斥,能夠達到數(shù)據(jù)保護的效果
同步: 多個線程之間按照事先約定好的順序有先后地完成某個事件
? (練習:創(chuàng)建兩個線程,一個從鍵盤獲取數(shù)據(jù),另一個打印輸出)
信號量:是系統(tǒng)中的一種資源,本質是一個非負整數(shù),信號量的值等于資源的個數(shù)。
操作信號量只能由通過特定函數(shù)接口才能訪問:
-
信號量的初始化 sem_init();
-
P操作(申請資源) sem_wait();
if(是否有資源) {執(zhí)行后續(xù)代碼;信號量 - 1; } else {阻塞等待,直到有資源喚醒為止; } -
V操作(釋放資源) sem_post();
信號量 + 1; if(有等待資源的程序) {喚醒程序; }
互斥: 當一個線程使用公共數(shù)據(jù)時,其他線程都不能訪問該公共數(shù)據(jù)
臨界資源 : 多個線程能夠共同訪問的數(shù)據(jù)
臨界區(qū) : 涉及到臨界資源的代碼模塊
互斥是使用 互斥鎖 保護臨界區(qū)
互斥鎖的相關操作接口函數(shù):
/* 互斥鎖的初始化 pthread_mutex_init() */ #include <pthread.h> int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr); 返回值:成功返回 0, 失敗返回 -1; 參數(shù):mutex: 互斥鎖對象mutexattr: 互斥鎖屬性,填NULL表示默認屬性 /* 申請鎖 pthread_mutex_loc() */ #include <pthread.h> int pthread_mutex_lock(pthread_mutex_t *mutex); 參數(shù):mutex: 互斥鎖對象 /* 釋放鎖 pthread_mutex_unlock() */ #include <pthread.h> int pthread_mutex_unlock(pthread_mutex_t *mutex); 參數(shù):mutex: 互斥鎖對象總結
以上是生活随笔為你收集整理的Linux 线程及线程间通信的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: EOS与金格iWebOffice集成应用
- 下一篇: linux 卸载vsftpd服务器,vs