上一篇部落格示範了一個最簡單的進程的建立過程,這篇部落格來示範一個最基礎的線程的例子。corecible回複我上篇博文時說:“不過真正的項目開發中,開子進 程用的很少。大多都是線程。”其實也說得挺有道理的,因為像java這樣的語言中,原生就支援線程,並提供了一套完整的通訊的方案。在linux中,線程實際上就是一個輕量級的進程,因為他們都是通過調用do_fork()函數,傳入不同的參數實現的。本來想先寫篇關於fork()實現分析的文章,後來考慮到線程和進程在linxu實現中的相同點,所以就先寫這篇博文了。
首先看個最基礎的線程的實現:
1 #include<stdio.h>
2 #include<pthread.h>
3
4
5 void *print_thread_id(void *arg)
6 {
7 /* 列印當前線程的線程號*/
8 printf("Current thread id is %u\n", (unsigned)pthread_self());
9 }
10
11 int main(int argc, char *argv[])
12 {
13 pthread_t thread; /*儲存線程號*/
14
15 /*建立一個線程 */
16 pthread_create(&thread, NULL, print_thread_id, NULL);
17
18 sleep(1); /*休眠1s*/
19
20 /*列印進程號 */
21 printf("Main thread id is %u\n", (unsigned)pthread_self());
22
23 return 0;
24 }
25
編譯的時候,一定要加上-lpthread選項,不然會報錯:undefined reference to `pthread_create'。
下面來看看pthread_create的聲明:
#include<pthread.h>
int pthread_create(pthread_t *thread, pthread_addr_t *arr,
void* (*start_routine)(void *), void *arg);
- thread :用於返回建立的線程的ID
- arr : 用於指定的被建立的線程的屬性,上面的函數中使用NULL,表示使用預設的屬性
- start_routine : 這是一個函數指標,指向線程被建立後要調用的函數
- arg : 用於給線程傳遞參數,在本例中沒有傳遞參數,所以使用了NULL
線程相對進程來說,有幾大優點,一是其切換速度快,其儲存現場花費的時間比進程少得多,二是:線程間的同步比進程簡單(至少我是這樣認為的)。當然,可能還有很多其他的優點我沒有發現,還請您多多指教。