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

成都創(chuàng)新互聯(lián)-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價比瑞安網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式瑞安網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋瑞安地區(qū)。費用合理售后完善,十載實體公司更值得信賴。
使用 pthread_create 方法建立線程
使用 pthread_create 是最常見的創(chuàng)建線程的方法,主要是因為它的語法簡單只需幾行代碼。它的原型如下:
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 為線程啟動時運行的函數(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ī)定新線程擁有和父進程完全相同的地址空間時,可以使用它來創(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)建線程時執(zhí)行的函數(shù)指針。
2、child_stack 子線程使用的堆棧指針。
3、flags 指定進程地址空間的復制方式。
4、arg 參數(shù)傳遞給 fn。
5、parent_tid 指向父線程 ID 的指針。
6、tls 指定注冊的 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ù)功能,就可以成功編寫出需要的多線程程序。
創(chuàng)新互聯(lián)服務(wù)器托管擁有成都T3+級標準機房資源,具備完善的安防設(shè)施、三線及BGP網(wǎng)絡(luò)接入帶寬達10T,機柜接入千兆交換機,能夠有效保證服務(wù)器托管業(yè)務(wù)安全、可靠、穩(wěn)定、高效運行;創(chuàng)新互聯(lián)專注于成都服務(wù)器托管租用十余年,得到成都等地區(qū)行業(yè)客戶的一致認可。
新聞標題:Linux環(huán)境下如何建立線程(linux建立線程)
標題URL:http://www.dlmjj.cn/article/dhgoisd.html


咨詢
建站咨詢
