線程:是在某個進程中被建立的,而它達到生命週期都在這個進程中。
線程它允許一個進程執行一個或多個執行路徑(即1個進程可以有多個線程,來執行不同的程式),這些執行路徑由系統非同步調度。
進程有自己的資料區段,程式碼片段,堆棧段。
而線程與進程的區別:
1. 程式碼片段一樣
2.資料區段一樣(全域變數)。
3.棧堆段不一樣!!!!!
建立線程的函數:
#include<pthread.h>
int pthread_create(pthread_t*thread,pthread_attr_t *attr,
void * (*start_routine)(void *arg),
void *arg);
功能:建立線程
傳回值:成功0
thread :程式的ID(標示符)。
attr:線程的屬性設定,如果為NULL,則建立系統預設的線程屬性。
start_routine:線程運行函數的起始地址。
最後一個參數是:線程運行函數的參數。
例子:
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
void *thfun(void *arg)
{ printf("new thread!\n");
printf("%s\n",(char*)arg);
return ((void *)0);
}
int main(int argc ,char *argv[])
{
int ret;
pthread_t pthid;
ret=pthread_create(&pthid,NULL,thfun,(void *)"hello");
// 第一個參數為線程ID,把它儲存在pthid中。
//If attr is NULL, the default attributes shall be used.
//第二個參數if是NULL,則建立預設屬性的進程。
// 。。。3。。線程運行函數的起始地址,
//..... 4.... 線程運行函數的參數。
If(ret!=1){
perror("can'tcreat thread ");
exit(EXIT_FAILURE);
}
printf("main thread!\n");
sleep(1);
exit(0);//return 0;
}
運行結果:
下面我們看個例子:
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
void *th_fun(void*arg)
{
printf("%s",arg);//列印傳遞的參數
while(1)
fputs("new thread \n",stdout);
//輸出字串new thread到標準輸出
return ((void*)0);
}
int main()
{
int ret;
pthread_t tid;
if((ret=pthread_create(&tid,NULL,th_fun,"new thread created!\n"))==-1)
{
perror("pthread_createerror ");
exit(EXIT_FAILURE);
}
while(1)
fputs("main thread \n",stdout);
//輸出字串main thread到標準輸出
return 0;
}
運行結果:
我們從運行結果來看,它一會輸出main thread ,一會輸出new thread
可以看出系統是對兩個線程進行調度。