歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux技術 >> Linux創建子線程

Linux創建子線程

日期:2017/3/3 12:32:52   编辑:Linux技術

創建一個子線程函數

******* utili.h *****************

#include <iostream>

#include <unistd.h>

#include <stdio.h>

#include <pthread.h>

using namespace std;

****** pthread.h ***************

#include "utili.h"

void* thread_fun(void *arg)

{

printf("this is child id = %d\n", pthread_self()); //pthread_self()是取的自己線程的ID(unix 網絡編程第二卷408頁)

int n = *(int *)arg;

for(int i = 0; i < n; ++i)

{

printf("This is Child Thread.\n");

}

}

int main(void)

{

pthread_t tid; //系統內部定的pthread_t 類型為unsigned long int

//相當於先申請一塊內存,用於存放生成的線程的tid 號

int n = 5;

//調用系統的線程創建函數

pthread_create(&tid, NULL, thread_fun, &n); //創建一個子線程,n 是傳給子線程函數的參數

sleep(1);

for(int i = 0; i <10; ++i)

{

printf("this is main Thread.\n");

}

char *retval;

pthread_join(tid, (void **)retval); //阻塞函數,等待一個線程的結束,一值到被等待的線程結束為止

printf("child thread exit code :> %d\n",*retval);//打印線程的退出值

return 0;

}

Copyright © Linux教程網 All Rights Reserved