av激情亚洲男人的天堂国语,日韩欧美精品一中文字幕,无码av一区二区三区无码,国产又色又爽又刺激的a片,国产又色又爽又刺激的a片

Linux環(huán)境下如何建立線程(linux建立線程)

在linux系統(tǒng)中建立線程實(shí)際上非常簡(jiǎn)單,主要有兩種方法:兩個(gè)函數(shù) pthread_CREATE 和 clone。

成都創(chuàng)新互聯(lián)-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價(jià)比瑞安網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式瑞安網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋瑞安地區(qū)。費(fèi)用合理售后完善,十載實(shí)體公司更值得信賴。

使用 pthread_create 方法建立線程

使用 pthread_create 是最常見的創(chuàng)建線程的方法,主要是因?yàn)樗恼Z法簡(jiǎn)單只需幾行代碼。它的原型如下:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);

它的參數(shù)介紹如下:

1、thread 創(chuàng)建成功后,返回線程 ID。

2、attr 指定線程屬性,通常設(shè)置為 NULL。

3、 start_routine 為線程啟動(dòng)時(shí)運(yùn)行的函數(shù)或程序段。

4、arg 傳遞給 start_routine 的參數(shù)。

例子:

#include

#include

void *print_message_function( void *ptr );

main()

{

pthread_t thread1, thread2;

const char *message1 = “Thread 1”;

const char *message2 = “Thread 2”;

int iret1, iret2;

iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);

iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);

pthread_join( thread1, NULL);

pthread_join( thread2, NULL);

printf(“Thread 1 returns: %d\n”, iret1);

printf(“Thread 2 returns: %d\n”, iret2);

exit(0);

}

void *print_message_function( void *ptr )

{

char *message;

message = (char *) ptr;

printf(“%s \n”, message);

}

使用 clone 方法建立線程

clone是Linux內(nèi)核規(guī)定新線程擁有和父進(jìn)程完全相同的地址空間時(shí),可以使用它來創(chuàng)建線程。它的原型如下:

int clone(int (*fn)(void *), void *child_stack, int flags, void *arg, int *parent_tid, struct user_desc *tls, int *child_tid);

它的參數(shù)介紹如下:

1、fn 創(chuàng)建線程時(shí)執(zhí)行的函數(shù)指針。

2、child_stack 子線程使用的堆棧指針。

3、flags 指定進(jìn)程地址空間的復(fù)制方式。

4、arg 參數(shù)傳遞給 fn。

5、parent_tid 指向父線程 ID 的指針。

6、tls 指定注冊(cè)的 TLS 段。

7、child_tid 返回子線程 ID 的指針。

例子:

#include

#include

#include

#define STACK_SIZE 1024 * 64

char child_stack[STACK_SIZE];

int thread_function(void *param)

{

printf(“I’m new thread!\n”);

return 0;

}

int main()

{

clone(thread_function, child_stack + STACK_SIZE,

CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM,

NULL);

printf(“Main thread finished!\n”);

return 0;

}

總而言之,在Linux環(huán)境下建立線程使用pthread_create和clone兩種方式,只要讀者在使用時(shí)分清楚兩種函數(shù)功能,就可以成功編寫出需要的多線程程序。

創(chuàng)新互聯(lián)服務(wù)器托管擁有成都T3+級(jí)標(biāo)準(zhǔn)機(jī)房資源,具備完善的安防設(shè)施、三線及BGP網(wǎng)絡(luò)接入帶寬達(dá)10T,機(jī)柜接入千兆交換機(jī),能夠有效保證服務(wù)器托管業(yè)務(wù)安全、可靠、穩(wěn)定、高效運(yùn)行;創(chuàng)新互聯(lián)專注于成都服務(wù)器托管租用十余年,得到成都等地區(qū)行業(yè)客戶的一致認(rèn)可。


網(wǎng)站欄目:Linux環(huán)境下如何建立線程(linux建立線程)
轉(zhuǎn)載注明:http://uogjgqi.cn/article/dhgoisd.html
掃二維碼與項(xiàng)目經(jīng)理溝通

我們?cè)谖⑿派?4小時(shí)期待你的聲音

解答本文疑問/技術(shù)咨詢/運(yùn)營(yíng)咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流