在linux中,線程實際上就是一個輕量級的進程,因爲他們都是通過調用do_fork()函數,傳入不同的參數實現的。
首先看個最基礎的線程的實現:
#include<stdio.h>
#include<pthread.h>
void *print_thread_id(void *arg)
{
/* 打印當前線程的線程號*/
printf("Current thread id is %u\n", (unsigned)pthread_self());
}
int main(int argc, char *argv[])
{
pthread_t thread; /*保存線程號*/
/*創建一個線程 */
pthread_create(&thread, NULL, print_thread_id, NULL);
sleep(1); /*休眠1s*/
/*打印進程號 */
printf("Main thread id is %u\n", (unsigned)pthread_self());
return 0;
}
編譯的時候,一定要加上-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
線程相對進程來說,有幾大優點,一是其切換速度快,其保存現場花費的時間比進程少得多,
二是:線程間的同步比進程簡單(至少我是這樣認爲的)。