linux程式設計 程序和執行緒的學習

2021-09-02 03:44:27 字數 2784 閱讀 3509

程序:程式**+資料+變數(占用著系統記憶體)+檔案描述符(開啟的檔案)+環境

p408模擬乙個鬧鐘alarm.c

執行緒:新的執行執行緒擁有自己的棧儲存區域性變數,但與他的建立者共享全域性變數、檔案描述符、訊號處理函式、當前目錄狀態。

#include #include #include #include //pause函式

#include static int alarm_fired = 0;//標誌

void ding(int sig)//模擬鬧鐘,引數為訊號

//告訴子程序在等待5秒後傳送乙個sigalrm訊號(超時警告)給他的父程序

int main()

//父程序通過乙個signal呼叫安排好捕獲訊號的工作,等待超時警告訊號的到來

//並未在訊號處理函式ding中使用printf,而是設定標誌位,在main函式中printf完成訊息輸出

printf("waiting for alarm to go off\n");

(void) signal(sigalrm, ding);

pause();//把程式暫時掛起,直到有乙個訊號出現為止,被訊號中斷時返回

if(alarm_fired)

printf("ding!\n");

printf("done\n");

exit(0);

}//使用訊號並掛起程式的執行很重要

//利用更健壯的訊號介面sigaction代替signal

#include #include #include void ouch(int sig)

int main()

}//ctrl + c組合鍵:看到訊息

//終止:ctrl+\組合鍵

訊號量:可以控制對一組相同物件那個的訪問,比如從5條可用的**線中分配1條給某個執行緒的情況,更適合用計數訊號量。

互斥量:控制任一時刻只能有乙個執行緒可以訪問一些共享記憶體

例子:用訊號量和雙線程實現統計從鍵盤輸入的字串個數

#include #include #include #include #include #include //訪問訊號量函式

const int work_size = 1024;

void *thread_function(void *arg);

sem_t bin_sem; //訊號量

char work_area[work_size];

int main()

res = pthread_create(&a_thread, null, thread_function, null); //新執行緒剛啟動會阻塞,程式往下執行

if (res != 0)

printf("input some text.enter 'end' to finish\n");

while (strncmp("end", work_area, 3) != 0)

printf("\nwaiting for thread to finish...\n");

res = pthread_join(a_thread, &thread_result);

if (res != 0)

printf("thread joined\n");

sem_destroy(&bin_sem);

exit(exit_success);

}void *thread_function(void *arg)

pthread_exit(null);

}

改進:讓主線程等到統計執行緒完成字串個數的統計後再繼續執行,可以使用互斥量!

鎖住某個物件,使得每次只能有乙個執行緒訪問它.

#include #include #include #include #include #include //使用互斥量對關鍵變數進行保護

#define work_size 1024

char work_area[work_size];

pthread_mutex_t work_mutex; //protects both work_area and time_to_exit

int time_to_exit = 0;

void *thread_function(void *arg);

int main()

res = pthread_create(&a_thread, null, thread_function, null); //新建執行緒

if (res != 0)

pthread_mutex_lock(&work_mutex); //上鎖,以下**需要被保護,同一時刻只能有乙個執行緒訪問

printf("input some text.enter 'end' to finish\n");

while (!time_to_exit) //沒有輸入end,繼續等待輸入字串

else

}pthread_mutex_unlock(&work_mutex);

}void *thread_function(void *arg) //統計輸入字串個數

}//end退出後,解鎖等待下一次輸入

time_to_exit = 1;

work_area[0] = '\0';

pthread_mutex_unlock(&work_mutex);

pthread_exit(0);

}//note:這裡沒有判斷是否加鎖,解鎖是否成功,而且通過輪詢的方式獲得結果的方法不是好的程式設計方式,實際中,應盡可能的使用訊號量來避免這種情況

linux程序和執行緒

這兩天一直在看linxu程序和執行緒的東西,總是效率比較低,這麼一點基礎的東西還看了這麼久。該自我反省一下。首先來看看程序。程序分為三個部分,程序控制塊,程式段和資料段。程序是乙個有生命的實體,程式是乙個沒有生命的實體。只有cpu賦予程式生命的時候,程式才成為乙個活動的實體,我們稱之為 程序 每乙個...

Linux程序和執行緒

linux核心只有程序,沒有執行緒的概念。非要說區別,那就是執行緒沒有自己的單獨的位址空間 mm struct 執行緒和其父程序共享位址空間。pthread呼叫fork clone vm 來建立新的程序,子程序與父程序共享vm空間。注意,這裡實際上是共享mm struct結構,子程序甚至沒有建立自己...

linux 程序和執行緒

程序和執行緒 程序 process 和執行緒 thread 是作業系統的基本概念,下面用乙個模擬,來解釋它們。1.計算機的核心是cpu,它承擔了所有的計算任務。它就像一座工廠,時刻在執行。2.假定工廠的電力有限,一次只能供給乙個車間使用。也就是說,乙個車間開工的時候,其他車間都必須停工。背後的含義就...